Noticed this on inspection, fix and update some comments.
[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 unless the object is an alloca from
613     // another block, otherwise it may not have a virtual register assigned.
614     if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
615         FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
616       Opcode = I->getOpcode();
617       U = I;
618     }
619   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
620     Opcode = C->getOpcode();
621     U = C;
622   }
623
624   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
625     if (Ty->getAddressSpace() > 255)
626       // Fast instruction selection doesn't support the special
627       // address spaces.
628       return false;
629
630   switch (Opcode) {
631     default:
632     break;
633     case Instruction::BitCast: {
634       // Look through bitcasts.
635       return ARMComputeAddress(U->getOperand(0), Addr);
636     }
637     case Instruction::IntToPtr: {
638       // Look past no-op inttoptrs.
639       if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
640         return ARMComputeAddress(U->getOperand(0), Addr);
641       break;
642     }
643     case Instruction::PtrToInt: {
644       // Look past no-op ptrtoints.
645       if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
646         return ARMComputeAddress(U->getOperand(0), Addr);
647       break;
648     }
649     case Instruction::GetElementPtr: {
650       Address SavedAddr = Addr;
651       int TmpOffset = Addr.Offset;
652
653       // Iterate through the GEP folding the constants into offsets where
654       // we can.
655       gep_type_iterator GTI = gep_type_begin(U);
656       for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
657            i != e; ++i, ++GTI) {
658         const Value *Op = *i;
659         if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
660           const StructLayout *SL = TD.getStructLayout(STy);
661           unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
662           TmpOffset += SL->getElementOffset(Idx);
663         } else {
664           uint64_t S = TD.getTypeAllocSize(GTI.getIndexedType());
665           SmallVector<const Value *, 4> Worklist;
666           Worklist.push_back(Op);
667           do {
668             Op = Worklist.pop_back_val();
669             if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
670               // Constant-offset addressing.
671               TmpOffset += CI->getSExtValue() * S;
672             } else if (isa<AddOperator>(Op) &&
673                        isa<ConstantInt>(cast<AddOperator>(Op)->getOperand(1))) {
674               // An add with a constant operand. Fold the constant.
675               ConstantInt *CI =
676                 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
677               TmpOffset += CI->getSExtValue() * S;
678               // Add the other operand back to the work list.
679               Worklist.push_back(cast<AddOperator>(Op)->getOperand(0));
680             } else
681               goto unsupported_gep;
682           } while (!Worklist.empty());
683         }
684       }
685
686       // Try to grab the base operand now.
687       Addr.Offset = TmpOffset;
688       if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
689
690       // We failed, restore everything and try the other options.
691       Addr = SavedAddr;
692
693       unsupported_gep:
694       break;
695     }
696     case Instruction::Alloca: {
697       const AllocaInst *AI = cast<AllocaInst>(Obj);
698       DenseMap<const AllocaInst*, int>::iterator SI =
699         FuncInfo.StaticAllocaMap.find(AI);
700       if (SI != FuncInfo.StaticAllocaMap.end()) {
701         Addr.BaseType = Address::FrameIndexBase;
702         Addr.Base.FI = SI->second;
703         return true;
704       }
705       break;
706     }
707   }
708
709   // Materialize the global variable's address into a reg which can
710   // then be used later to load the variable.
711   if (const GlobalValue *GV = dyn_cast<GlobalValue>(Obj)) {
712     unsigned Tmp = ARMMaterializeGV(GV, TLI.getValueType(Obj->getType()));
713     if (Tmp == 0) return false;
714
715     Addr.Base.Reg = Tmp;
716     return true;
717   }
718
719   // Try to get this in a register if nothing else has worked.
720   if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
721   return Addr.Base.Reg != 0;
722 }
723
724 void ARMFastISel::ARMSimplifyAddress(Address &Addr, EVT VT) {
725
726   assert(VT.isSimple() && "Non-simple types are invalid here!");
727
728   bool needsLowering = false;
729   switch (VT.getSimpleVT().SimpleTy) {
730     default:
731       assert(false && "Unhandled load/store type!");
732     case MVT::i1:
733     case MVT::i8:
734     case MVT::i16:
735     case MVT::i32:
736       // Integer loads/stores handle 12-bit offsets.
737       needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
738       break;
739     case MVT::f32:
740     case MVT::f64:
741       // Floating point operands handle 8-bit offsets.
742       needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
743       break;
744   }
745
746   // If this is a stack pointer and the offset needs to be simplified then
747   // put the alloca address into a register, set the base type back to
748   // register and continue. This should almost never happen.
749   if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
750     TargetRegisterClass *RC = isThumb ? ARM::tGPRRegisterClass :
751                               ARM::GPRRegisterClass;
752     unsigned ResultReg = createResultReg(RC);
753     unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
754     AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
755                             TII.get(Opc), ResultReg)
756                             .addFrameIndex(Addr.Base.FI)
757                             .addImm(0));
758     Addr.Base.Reg = ResultReg;
759     Addr.BaseType = Address::RegBase;
760   }
761
762   // Since the offset is too large for the load/store instruction
763   // get the reg+offset into a register.
764   if (needsLowering) {
765     ARMCC::CondCodes Pred = ARMCC::AL;
766     unsigned PredReg = 0;
767
768     TargetRegisterClass *RC = isThumb ? ARM::tGPRRegisterClass :
769       ARM::GPRRegisterClass;
770     unsigned BaseReg = createResultReg(RC);
771
772     if (!isThumb)
773       emitARMRegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
774                               BaseReg, Addr.Base.Reg, Addr.Offset,
775                               Pred, PredReg,
776                               static_cast<const ARMBaseInstrInfo&>(TII));
777     else {
778       assert(AFI->isThumb2Function());
779       emitT2RegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
780                              BaseReg, Addr.Base.Reg, Addr.Offset, Pred, PredReg,
781                              static_cast<const ARMBaseInstrInfo&>(TII));
782     }
783     Addr.Offset = 0;
784     Addr.Base.Reg = BaseReg;
785   }
786 }
787
788 bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg, Address &Addr) {
789
790   assert(VT.isSimple() && "Non-simple types are invalid here!");
791   unsigned Opc;
792   TargetRegisterClass *RC;
793   bool isFloat = false;
794   switch (VT.getSimpleVT().SimpleTy) {
795     default:
796       // This is mostly going to be Neon/vector support.
797       return false;
798     case MVT::i16:
799       Opc = isThumb ? ARM::t2LDRHi12 : ARM::LDRH;
800       RC = ARM::GPRRegisterClass;
801       break;
802     case MVT::i8:
803       Opc = isThumb ? ARM::t2LDRBi12 : ARM::LDRBi12;
804       RC = ARM::GPRRegisterClass;
805       break;
806     case MVT::i32:
807       Opc = isThumb ? ARM::t2LDRi12 : ARM::LDRi12;
808       RC = ARM::GPRRegisterClass;
809       break;
810     case MVT::f32:
811       Opc = ARM::VLDRS;
812       RC = TLI.getRegClassFor(VT);
813       isFloat = true;
814       break;
815     case MVT::f64:
816       Opc = ARM::VLDRD;
817       RC = TLI.getRegClassFor(VT);
818       isFloat = true;
819       break;
820   }
821
822   ResultReg = createResultReg(RC);
823
824   ARMSimplifyAddress(Addr, VT);
825
826   // addrmode5 output depends on the selection dag addressing dividing the
827   // offset by 4 that it then later multiplies. Do this here as well.
828   if (isFloat)
829     Addr.Offset /= 4;
830
831   if (Addr.BaseType == Address::FrameIndexBase) {
832     int FI = Addr.Base.FI;
833     int Offset = Addr.Offset;
834     MachineMemOperand *MMO =
835           FuncInfo.MF->getMachineMemOperand(
836                                   MachinePointerInfo::getFixedStack(FI, Offset),
837                                   MachineMemOperand::MOLoad,
838                                   MFI.getObjectSize(FI),
839                                   MFI.getObjectAlignment(FI));
840     // LDRH needs an additional operand.
841     if (!isThumb && VT.getSimpleVT().SimpleTy == MVT::i16)
842       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
843                               TII.get(Opc), ResultReg)
844                       .addFrameIndex(FI).addReg(0).addImm(Offset)
845                       .addMemOperand(MMO));
846     else
847       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
848                               TII.get(Opc), ResultReg)
849                       .addFrameIndex(FI).addImm(Offset).addMemOperand(MMO));
850     return true;
851   }
852
853   // LDRH needs an additional operand.
854   if (!isThumb && VT.getSimpleVT().SimpleTy == MVT::i16)
855     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
856                             TII.get(Opc), ResultReg)
857                     .addReg(Addr.Base.Reg).addReg(0).addImm(Addr.Offset));
858   else
859     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
860                             TII.get(Opc), ResultReg)
861                     .addReg(Addr.Base.Reg).addImm(Addr.Offset));
862   return true;
863 }
864
865 bool ARMFastISel::SelectLoad(const Instruction *I) {
866   // Verify we have a legal type before going any further.
867   MVT VT;
868   if (!isLoadTypeLegal(I->getType(), VT))
869     return false;
870
871   // Our register and offset with innocuous defaults.
872   Address Addr;
873
874   // See if we can handle this as Reg + Offset
875   if (!ARMComputeAddress(I->getOperand(0), Addr))
876     return false;
877
878   unsigned ResultReg;
879   if (!ARMEmitLoad(VT, ResultReg, Addr)) return false;
880
881   UpdateValueMap(I, ResultReg);
882   return true;
883 }
884
885 bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg, Address &Addr) {
886   unsigned StrOpc;
887   bool isFloat = false;
888   switch (VT.getSimpleVT().SimpleTy) {
889     default: return false;
890     case MVT::i1: {
891       unsigned Res = createResultReg(isThumb ? ARM::tGPRRegisterClass :
892                                                ARM::GPRRegisterClass);
893       unsigned Opc = isThumb ? ARM::t2ANDri : ARM::ANDri;
894       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
895                               TII.get(Opc), Res)
896                       .addReg(SrcReg).addImm(1));
897       SrcReg = Res;
898     } // Fallthrough here.
899     case MVT::i8:
900       StrOpc = isThumb ? ARM::t2STRBi12 : ARM::STRBi12;
901       break;
902     case MVT::i16:
903       StrOpc = isThumb ? ARM::t2STRHi12 : ARM::STRH;
904       break;
905     case MVT::i32:
906       StrOpc = isThumb ? ARM::t2STRi12 : ARM::STRi12;
907       break;
908     case MVT::f32:
909       if (!Subtarget->hasVFP2()) return false;
910       StrOpc = ARM::VSTRS;
911       isFloat = true;
912       break;
913     case MVT::f64:
914       if (!Subtarget->hasVFP2()) return false;
915       StrOpc = ARM::VSTRD;
916       isFloat = true;
917       break;
918   }
919
920   ARMSimplifyAddress(Addr, VT);
921
922   // addrmode5 output depends on the selection dag addressing dividing the
923   // offset by 4 that it then later multiplies. Do this here as well.
924   if (isFloat)
925     Addr.Offset /= 4;
926
927   if (Addr.BaseType == Address::FrameIndexBase) {
928     int FI = Addr.Base.FI;
929     int Offset = Addr.Offset;
930     MachineMemOperand *MMO =
931           FuncInfo.MF->getMachineMemOperand(
932                                   MachinePointerInfo::getFixedStack(FI, Offset),
933                                   MachineMemOperand::MOLoad,
934                                   MFI.getObjectSize(FI),
935                                   MFI.getObjectAlignment(FI));
936     // ARM::STRH needs an additional operand.
937     if (!isThumb && VT.getSimpleVT().SimpleTy == MVT::i16)
938       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
939                               TII.get(StrOpc))
940                       .addReg(SrcReg, getKillRegState(true))
941                       .addFrameIndex(FI).addReg(0).addImm(Offset)
942                       .addMemOperand(MMO));
943     else
944       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
945                               TII.get(StrOpc))
946                       .addReg(SrcReg, getKillRegState(true))
947                       .addFrameIndex(FI).addImm(Offset).addMemOperand(MMO));
948
949     return true;
950   }
951
952   // ARM::STRH needs an additional operand.
953   if (!isThumb && VT.getSimpleVT().SimpleTy == MVT::i16)
954     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
955                             TII.get(StrOpc))
956                     .addReg(SrcReg).addReg(Addr.Base.Reg)
957                     .addReg(0).addImm(Addr.Offset));
958   else
959     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
960                             TII.get(StrOpc))
961                     .addReg(SrcReg).addReg(Addr.Base.Reg).addImm(Addr.Offset));
962
963   return true;
964 }
965
966 bool ARMFastISel::SelectStore(const Instruction *I) {
967   Value *Op0 = I->getOperand(0);
968   unsigned SrcReg = 0;
969
970   // Yay type legalization
971   MVT VT;
972   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
973     return false;
974
975   // Get the value to be stored into a register.
976   SrcReg = getRegForValue(Op0);
977   if (SrcReg == 0)
978     return false;
979
980   // Our register and offset with innocuous defaults.
981   Address Addr;
982
983   // See if we can handle this as Reg + Offset
984   if (!ARMComputeAddress(I->getOperand(1), Addr))
985     return false;
986
987   if (!ARMEmitStore(VT, SrcReg, Addr)) return false;
988
989   return true;
990 }
991
992 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
993   switch (Pred) {
994     // Needs two compares...
995     case CmpInst::FCMP_ONE:
996     case CmpInst::FCMP_UEQ:
997     default:
998       // AL is our "false" for now. The other two need more compares.
999       return ARMCC::AL;
1000     case CmpInst::ICMP_EQ:
1001     case CmpInst::FCMP_OEQ:
1002       return ARMCC::EQ;
1003     case CmpInst::ICMP_SGT:
1004     case CmpInst::FCMP_OGT:
1005       return ARMCC::GT;
1006     case CmpInst::ICMP_SGE:
1007     case CmpInst::FCMP_OGE:
1008       return ARMCC::GE;
1009     case CmpInst::ICMP_UGT:
1010     case CmpInst::FCMP_UGT:
1011       return ARMCC::HI;
1012     case CmpInst::FCMP_OLT:
1013       return ARMCC::MI;
1014     case CmpInst::ICMP_ULE:
1015     case CmpInst::FCMP_OLE:
1016       return ARMCC::LS;
1017     case CmpInst::FCMP_ORD:
1018       return ARMCC::VC;
1019     case CmpInst::FCMP_UNO:
1020       return ARMCC::VS;
1021     case CmpInst::FCMP_UGE:
1022       return ARMCC::PL;
1023     case CmpInst::ICMP_SLT:
1024     case CmpInst::FCMP_ULT:
1025       return ARMCC::LT;
1026     case CmpInst::ICMP_SLE:
1027     case CmpInst::FCMP_ULE:
1028       return ARMCC::LE;
1029     case CmpInst::FCMP_UNE:
1030     case CmpInst::ICMP_NE:
1031       return ARMCC::NE;
1032     case CmpInst::ICMP_UGE:
1033       return ARMCC::HS;
1034     case CmpInst::ICMP_ULT:
1035       return ARMCC::LO;
1036   }
1037 }
1038
1039 bool ARMFastISel::SelectBranch(const Instruction *I) {
1040   const BranchInst *BI = cast<BranchInst>(I);
1041   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1042   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1043
1044   // Simple branch support.
1045
1046   // If we can, avoid recomputing the compare - redoing it could lead to wonky
1047   // behavior.
1048   // TODO: Factor this out.
1049   if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1050     if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1051       MVT VT;
1052       const Type *Ty = CI->getOperand(0)->getType();
1053       if (!isTypeLegal(Ty, VT))
1054         return false;
1055
1056       bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1057       if (isFloat && !Subtarget->hasVFP2())
1058         return false;
1059
1060       unsigned CmpOpc;
1061       unsigned CondReg;
1062       switch (VT.SimpleTy) {
1063         default: return false;
1064         // TODO: Verify compares.
1065         case MVT::f32:
1066           CmpOpc = ARM::VCMPES;
1067           CondReg = ARM::FPSCR;
1068           break;
1069         case MVT::f64:
1070           CmpOpc = ARM::VCMPED;
1071           CondReg = ARM::FPSCR;
1072           break;
1073         case MVT::i32:
1074           CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
1075           CondReg = ARM::CPSR;
1076           break;
1077       }
1078
1079       // Get the compare predicate.
1080       ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1081
1082       // We may not handle every CC for now.
1083       if (ARMPred == ARMCC::AL) return false;
1084
1085       unsigned Arg1 = getRegForValue(CI->getOperand(0));
1086       if (Arg1 == 0) return false;
1087
1088       unsigned Arg2 = getRegForValue(CI->getOperand(1));
1089       if (Arg2 == 0) return false;
1090
1091       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1092                               TII.get(CmpOpc))
1093                       .addReg(Arg1).addReg(Arg2));
1094
1095       // For floating point we need to move the result to a comparison register
1096       // that we can then use for branches.
1097       if (isFloat)
1098         AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1099                                 TII.get(ARM::FMSTAT)));
1100
1101       unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
1102       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1103       .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1104       FastEmitBranch(FBB, DL);
1105       FuncInfo.MBB->addSuccessor(TBB);
1106       return true;
1107     }
1108   }
1109
1110   unsigned CmpReg = getRegForValue(BI->getCondition());
1111   if (CmpReg == 0) return false;
1112
1113   // Re-set the flags just in case.
1114   unsigned CmpOpc = isThumb ? ARM::t2CMPri : ARM::CMPri;
1115   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1116                   .addReg(CmpReg).addImm(0));
1117
1118   unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
1119   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
1120                   .addMBB(TBB).addImm(ARMCC::NE).addReg(ARM::CPSR);
1121   FastEmitBranch(FBB, DL);
1122   FuncInfo.MBB->addSuccessor(TBB);
1123   return true;
1124 }
1125
1126 bool ARMFastISel::SelectCmp(const Instruction *I) {
1127   const CmpInst *CI = cast<CmpInst>(I);
1128
1129   MVT VT;
1130   const Type *Ty = CI->getOperand(0)->getType();
1131   if (!isTypeLegal(Ty, VT))
1132     return false;
1133
1134   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1135   if (isFloat && !Subtarget->hasVFP2())
1136     return false;
1137
1138   unsigned CmpOpc;
1139   unsigned CondReg;
1140   switch (VT.SimpleTy) {
1141     default: return false;
1142     // TODO: Verify compares.
1143     case MVT::f32:
1144       CmpOpc = ARM::VCMPES;
1145       CondReg = ARM::FPSCR;
1146       break;
1147     case MVT::f64:
1148       CmpOpc = ARM::VCMPED;
1149       CondReg = ARM::FPSCR;
1150       break;
1151     case MVT::i32:
1152       CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
1153       CondReg = ARM::CPSR;
1154       break;
1155   }
1156
1157   // Get the compare predicate.
1158   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1159
1160   // We may not handle every CC for now.
1161   if (ARMPred == ARMCC::AL) return false;
1162
1163   unsigned Arg1 = getRegForValue(CI->getOperand(0));
1164   if (Arg1 == 0) return false;
1165
1166   unsigned Arg2 = getRegForValue(CI->getOperand(1));
1167   if (Arg2 == 0) return false;
1168
1169   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1170                   .addReg(Arg1).addReg(Arg2));
1171
1172   // For floating point we need to move the result to a comparison register
1173   // that we can then use for branches.
1174   if (isFloat)
1175     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1176                             TII.get(ARM::FMSTAT)));
1177
1178   // Now set a register based on the comparison. Explicitly set the predicates
1179   // here.
1180   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCi : ARM::MOVCCi;
1181   TargetRegisterClass *RC = isThumb ? ARM::rGPRRegisterClass
1182                                     : ARM::GPRRegisterClass;
1183   unsigned DestReg = createResultReg(RC);
1184   Constant *Zero
1185     = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1186   unsigned ZeroReg = TargetMaterializeConstant(Zero);
1187   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
1188           .addReg(ZeroReg).addImm(1)
1189           .addImm(ARMPred).addReg(CondReg);
1190
1191   UpdateValueMap(I, DestReg);
1192   return true;
1193 }
1194
1195 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1196   // Make sure we have VFP and that we're extending float to double.
1197   if (!Subtarget->hasVFP2()) return false;
1198
1199   Value *V = I->getOperand(0);
1200   if (!I->getType()->isDoubleTy() ||
1201       !V->getType()->isFloatTy()) return false;
1202
1203   unsigned Op = getRegForValue(V);
1204   if (Op == 0) return false;
1205
1206   unsigned Result = createResultReg(ARM::DPRRegisterClass);
1207   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1208                           TII.get(ARM::VCVTDS), Result)
1209                   .addReg(Op));
1210   UpdateValueMap(I, Result);
1211   return true;
1212 }
1213
1214 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1215   // Make sure we have VFP and that we're truncating double to float.
1216   if (!Subtarget->hasVFP2()) return false;
1217
1218   Value *V = I->getOperand(0);
1219   if (!(I->getType()->isFloatTy() &&
1220         V->getType()->isDoubleTy())) return false;
1221
1222   unsigned Op = getRegForValue(V);
1223   if (Op == 0) return false;
1224
1225   unsigned Result = createResultReg(ARM::SPRRegisterClass);
1226   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1227                           TII.get(ARM::VCVTSD), Result)
1228                   .addReg(Op));
1229   UpdateValueMap(I, Result);
1230   return true;
1231 }
1232
1233 bool ARMFastISel::SelectSIToFP(const Instruction *I) {
1234   // Make sure we have VFP.
1235   if (!Subtarget->hasVFP2()) return false;
1236
1237   MVT DstVT;
1238   const Type *Ty = I->getType();
1239   if (!isTypeLegal(Ty, DstVT))
1240     return false;
1241
1242   unsigned Op = getRegForValue(I->getOperand(0));
1243   if (Op == 0) return false;
1244
1245   // The conversion routine works on fp-reg to fp-reg and the operand above
1246   // was an integer, move it to the fp registers if possible.
1247   unsigned FP = ARMMoveToFPReg(MVT::f32, Op);
1248   if (FP == 0) return false;
1249
1250   unsigned Opc;
1251   if (Ty->isFloatTy()) Opc = ARM::VSITOS;
1252   else if (Ty->isDoubleTy()) Opc = ARM::VSITOD;
1253   else return 0;
1254
1255   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1256   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1257                           ResultReg)
1258                   .addReg(FP));
1259   UpdateValueMap(I, ResultReg);
1260   return true;
1261 }
1262
1263 bool ARMFastISel::SelectFPToSI(const Instruction *I) {
1264   // Make sure we have VFP.
1265   if (!Subtarget->hasVFP2()) return false;
1266
1267   MVT DstVT;
1268   const Type *RetTy = I->getType();
1269   if (!isTypeLegal(RetTy, DstVT))
1270     return false;
1271
1272   unsigned Op = getRegForValue(I->getOperand(0));
1273   if (Op == 0) return false;
1274
1275   unsigned Opc;
1276   const Type *OpTy = I->getOperand(0)->getType();
1277   if (OpTy->isFloatTy()) Opc = ARM::VTOSIZS;
1278   else if (OpTy->isDoubleTy()) Opc = ARM::VTOSIZD;
1279   else return 0;
1280
1281   // f64->s32 or f32->s32 both need an intermediate f32 reg.
1282   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1283   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1284                           ResultReg)
1285                   .addReg(Op));
1286
1287   // This result needs to be in an integer register, but the conversion only
1288   // takes place in fp-regs.
1289   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1290   if (IntReg == 0) return false;
1291
1292   UpdateValueMap(I, IntReg);
1293   return true;
1294 }
1295
1296 bool ARMFastISel::SelectSelect(const Instruction *I) {
1297   MVT VT;
1298   if (!isTypeLegal(I->getType(), VT))
1299     return false;
1300
1301   // Things need to be register sized for register moves.
1302   if (VT != MVT::i32) return false;
1303   const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1304
1305   unsigned CondReg = getRegForValue(I->getOperand(0));
1306   if (CondReg == 0) return false;
1307   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1308   if (Op1Reg == 0) return false;
1309   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1310   if (Op2Reg == 0) return false;
1311
1312   unsigned CmpOpc = isThumb ? ARM::t2TSTri : ARM::TSTri;
1313   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1314                   .addReg(CondReg).addImm(1));
1315   unsigned ResultReg = createResultReg(RC);
1316   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCr : ARM::MOVCCr;
1317   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1318     .addReg(Op1Reg).addReg(Op2Reg)
1319     .addImm(ARMCC::EQ).addReg(ARM::CPSR);
1320   UpdateValueMap(I, ResultReg);
1321   return true;
1322 }
1323
1324 bool ARMFastISel::SelectSDiv(const Instruction *I) {
1325   MVT VT;
1326   const Type *Ty = I->getType();
1327   if (!isTypeLegal(Ty, VT))
1328     return false;
1329
1330   // If we have integer div support we should have selected this automagically.
1331   // In case we have a real miss go ahead and return false and we'll pick
1332   // it up later.
1333   if (Subtarget->hasDivide()) return false;
1334
1335   // Otherwise emit a libcall.
1336   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1337   if (VT == MVT::i8)
1338     LC = RTLIB::SDIV_I8;
1339   else if (VT == MVT::i16)
1340     LC = RTLIB::SDIV_I16;
1341   else if (VT == MVT::i32)
1342     LC = RTLIB::SDIV_I32;
1343   else if (VT == MVT::i64)
1344     LC = RTLIB::SDIV_I64;
1345   else if (VT == MVT::i128)
1346     LC = RTLIB::SDIV_I128;
1347   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1348
1349   return ARMEmitLibcall(I, LC);
1350 }
1351
1352 bool ARMFastISel::SelectSRem(const Instruction *I) {
1353   MVT VT;
1354   const Type *Ty = I->getType();
1355   if (!isTypeLegal(Ty, VT))
1356     return false;
1357
1358   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1359   if (VT == MVT::i8)
1360     LC = RTLIB::SREM_I8;
1361   else if (VT == MVT::i16)
1362     LC = RTLIB::SREM_I16;
1363   else if (VT == MVT::i32)
1364     LC = RTLIB::SREM_I32;
1365   else if (VT == MVT::i64)
1366     LC = RTLIB::SREM_I64;
1367   else if (VT == MVT::i128)
1368     LC = RTLIB::SREM_I128;
1369   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1370
1371   return ARMEmitLibcall(I, LC);
1372 }
1373
1374 bool ARMFastISel::SelectBinaryOp(const Instruction *I, unsigned ISDOpcode) {
1375   EVT VT  = TLI.getValueType(I->getType(), true);
1376
1377   // We can get here in the case when we want to use NEON for our fp
1378   // operations, but can't figure out how to. Just use the vfp instructions
1379   // if we have them.
1380   // FIXME: It'd be nice to use NEON instructions.
1381   const Type *Ty = I->getType();
1382   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1383   if (isFloat && !Subtarget->hasVFP2())
1384     return false;
1385
1386   unsigned Op1 = getRegForValue(I->getOperand(0));
1387   if (Op1 == 0) return false;
1388
1389   unsigned Op2 = getRegForValue(I->getOperand(1));
1390   if (Op2 == 0) return false;
1391
1392   unsigned Opc;
1393   bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1394   switch (ISDOpcode) {
1395     default: return false;
1396     case ISD::FADD:
1397       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1398       break;
1399     case ISD::FSUB:
1400       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1401       break;
1402     case ISD::FMUL:
1403       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1404       break;
1405   }
1406   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1407   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1408                           TII.get(Opc), ResultReg)
1409                   .addReg(Op1).addReg(Op2));
1410   UpdateValueMap(I, ResultReg);
1411   return true;
1412 }
1413
1414 // Call Handling Code
1415
1416 bool ARMFastISel::FastEmitExtend(ISD::NodeType Opc, EVT DstVT, unsigned Src,
1417                                  EVT SrcVT, unsigned &ResultReg) {
1418   unsigned RR = FastEmit_r(SrcVT.getSimpleVT(), DstVT.getSimpleVT(), Opc,
1419                            Src, /*TODO: Kill=*/false);
1420
1421   if (RR != 0) {
1422     ResultReg = RR;
1423     return true;
1424   } else
1425     return false;
1426 }
1427
1428 // This is largely taken directly from CCAssignFnForNode - we don't support
1429 // varargs in FastISel so that part has been removed.
1430 // TODO: We may not support all of this.
1431 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1432   switch (CC) {
1433   default:
1434     llvm_unreachable("Unsupported calling convention");
1435   case CallingConv::Fast:
1436     // Ignore fastcc. Silence compiler warnings.
1437     (void)RetFastCC_ARM_APCS;
1438     (void)FastCC_ARM_APCS;
1439     // Fallthrough
1440   case CallingConv::C:
1441     // Use target triple & subtarget features to do actual dispatch.
1442     if (Subtarget->isAAPCS_ABI()) {
1443       if (Subtarget->hasVFP2() &&
1444           FloatABIType == FloatABI::Hard)
1445         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1446       else
1447         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1448     } else
1449         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1450   case CallingConv::ARM_AAPCS_VFP:
1451     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1452   case CallingConv::ARM_AAPCS:
1453     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1454   case CallingConv::ARM_APCS:
1455     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1456   }
1457 }
1458
1459 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1460                                   SmallVectorImpl<unsigned> &ArgRegs,
1461                                   SmallVectorImpl<MVT> &ArgVTs,
1462                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1463                                   SmallVectorImpl<unsigned> &RegArgs,
1464                                   CallingConv::ID CC,
1465                                   unsigned &NumBytes) {
1466   SmallVector<CCValAssign, 16> ArgLocs;
1467   CCState CCInfo(CC, false, TM, ArgLocs, *Context);
1468   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1469
1470   // Get a count of how many bytes are to be pushed on the stack.
1471   NumBytes = CCInfo.getNextStackOffset();
1472
1473   // Issue CALLSEQ_START
1474   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1475   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1476                           TII.get(AdjStackDown))
1477                   .addImm(NumBytes));
1478
1479   // Process the args.
1480   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1481     CCValAssign &VA = ArgLocs[i];
1482     unsigned Arg = ArgRegs[VA.getValNo()];
1483     MVT ArgVT = ArgVTs[VA.getValNo()];
1484
1485     // We don't handle NEON parameters yet.
1486     if (VA.getLocVT().isVector() && VA.getLocVT().getSizeInBits() > 64)
1487       return false;
1488
1489     // Handle arg promotion, etc.
1490     switch (VA.getLocInfo()) {
1491       case CCValAssign::Full: break;
1492       case CCValAssign::SExt: {
1493         bool Emitted = FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1494                                          Arg, ArgVT, Arg);
1495         assert(Emitted && "Failed to emit a sext!"); Emitted=Emitted;
1496         Emitted = true;
1497         ArgVT = VA.getLocVT();
1498         break;
1499       }
1500       case CCValAssign::ZExt: {
1501         bool Emitted = FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1502                                          Arg, ArgVT, Arg);
1503         assert(Emitted && "Failed to emit a zext!"); Emitted=Emitted;
1504         Emitted = true;
1505         ArgVT = VA.getLocVT();
1506         break;
1507       }
1508       case CCValAssign::AExt: {
1509         bool Emitted = FastEmitExtend(ISD::ANY_EXTEND, VA.getLocVT(),
1510                                          Arg, ArgVT, Arg);
1511         if (!Emitted)
1512           Emitted = FastEmitExtend(ISD::ZERO_EXTEND, VA.getLocVT(),
1513                                       Arg, ArgVT, Arg);
1514         if (!Emitted)
1515           Emitted = FastEmitExtend(ISD::SIGN_EXTEND, VA.getLocVT(),
1516                                       Arg, ArgVT, Arg);
1517
1518         assert(Emitted && "Failed to emit a aext!"); Emitted=Emitted;
1519         ArgVT = VA.getLocVT();
1520         break;
1521       }
1522       case CCValAssign::BCvt: {
1523         unsigned BC = FastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1524                                  /*TODO: Kill=*/false);
1525         assert(BC != 0 && "Failed to emit a bitcast!");
1526         Arg = BC;
1527         ArgVT = VA.getLocVT();
1528         break;
1529       }
1530       default: llvm_unreachable("Unknown arg promotion!");
1531     }
1532
1533     // Now copy/store arg to correct locations.
1534     if (VA.isRegLoc() && !VA.needsCustom()) {
1535       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1536               VA.getLocReg())
1537       .addReg(Arg);
1538       RegArgs.push_back(VA.getLocReg());
1539     } else if (VA.needsCustom()) {
1540       // TODO: We need custom lowering for vector (v2f64) args.
1541       if (VA.getLocVT() != MVT::f64) return false;
1542
1543       CCValAssign &NextVA = ArgLocs[++i];
1544
1545       // TODO: Only handle register args for now.
1546       if(!(VA.isRegLoc() && NextVA.isRegLoc())) return false;
1547
1548       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1549                               TII.get(ARM::VMOVRRD), VA.getLocReg())
1550                       .addReg(NextVA.getLocReg(), RegState::Define)
1551                       .addReg(Arg));
1552       RegArgs.push_back(VA.getLocReg());
1553       RegArgs.push_back(NextVA.getLocReg());
1554     } else {
1555       assert(VA.isMemLoc());
1556       // Need to store on the stack.
1557       Address Addr;
1558       Addr.BaseType = Address::RegBase;
1559       Addr.Base.Reg = ARM::SP;
1560       Addr.Offset = VA.getLocMemOffset();
1561
1562       if (!ARMEmitStore(ArgVT, Arg, Addr)) return false;
1563     }
1564   }
1565   return true;
1566 }
1567
1568 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1569                              const Instruction *I, CallingConv::ID CC,
1570                              unsigned &NumBytes) {
1571   // Issue CALLSEQ_END
1572   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1573   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1574                           TII.get(AdjStackUp))
1575                   .addImm(NumBytes).addImm(0));
1576
1577   // Now the return value.
1578   if (RetVT != MVT::isVoid) {
1579     SmallVector<CCValAssign, 16> RVLocs;
1580     CCState CCInfo(CC, false, TM, RVLocs, *Context);
1581     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1582
1583     // Copy all of the result registers out of their specified physreg.
1584     if (RVLocs.size() == 2 && RetVT == MVT::f64) {
1585       // For this move we copy into two registers and then move into the
1586       // double fp reg we want.
1587       EVT DestVT = RVLocs[0].getValVT();
1588       TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1589       unsigned ResultReg = createResultReg(DstRC);
1590       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1591                               TII.get(ARM::VMOVDRR), ResultReg)
1592                       .addReg(RVLocs[0].getLocReg())
1593                       .addReg(RVLocs[1].getLocReg()));
1594
1595       UsedRegs.push_back(RVLocs[0].getLocReg());
1596       UsedRegs.push_back(RVLocs[1].getLocReg());
1597
1598       // Finally update the result.
1599       UpdateValueMap(I, ResultReg);
1600     } else {
1601       assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
1602       EVT CopyVT = RVLocs[0].getValVT();
1603       TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1604
1605       unsigned ResultReg = createResultReg(DstRC);
1606       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1607               ResultReg).addReg(RVLocs[0].getLocReg());
1608       UsedRegs.push_back(RVLocs[0].getLocReg());
1609
1610       // Finally update the result.
1611       UpdateValueMap(I, ResultReg);
1612     }
1613   }
1614
1615   return true;
1616 }
1617
1618 bool ARMFastISel::SelectRet(const Instruction *I) {
1619   const ReturnInst *Ret = cast<ReturnInst>(I);
1620   const Function &F = *I->getParent()->getParent();
1621
1622   if (!FuncInfo.CanLowerReturn)
1623     return false;
1624
1625   if (F.isVarArg())
1626     return false;
1627
1628   CallingConv::ID CC = F.getCallingConv();
1629   if (Ret->getNumOperands() > 0) {
1630     SmallVector<ISD::OutputArg, 4> Outs;
1631     GetReturnInfo(F.getReturnType(), F.getAttributes().getRetAttributes(),
1632                   Outs, TLI);
1633
1634     // Analyze operands of the call, assigning locations to each operand.
1635     SmallVector<CCValAssign, 16> ValLocs;
1636     CCState CCInfo(CC, F.isVarArg(), TM, ValLocs, I->getContext());
1637     CCInfo.AnalyzeReturn(Outs, CCAssignFnForCall(CC, true /* is Ret */));
1638
1639     const Value *RV = Ret->getOperand(0);
1640     unsigned Reg = getRegForValue(RV);
1641     if (Reg == 0)
1642       return false;
1643
1644     // Only handle a single return value for now.
1645     if (ValLocs.size() != 1)
1646       return false;
1647
1648     CCValAssign &VA = ValLocs[0];
1649
1650     // Don't bother handling odd stuff for now.
1651     if (VA.getLocInfo() != CCValAssign::Full)
1652       return false;
1653     // Only handle register returns for now.
1654     if (!VA.isRegLoc())
1655       return false;
1656     // TODO: For now, don't try to handle cases where getLocInfo()
1657     // says Full but the types don't match.
1658     if (TLI.getValueType(RV->getType()) != VA.getValVT())
1659       return false;
1660
1661     // Make the copy.
1662     unsigned SrcReg = Reg + VA.getValNo();
1663     unsigned DstReg = VA.getLocReg();
1664     const TargetRegisterClass* SrcRC = MRI.getRegClass(SrcReg);
1665     // Avoid a cross-class copy. This is very unlikely.
1666     if (!SrcRC->contains(DstReg))
1667       return false;
1668     BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1669             DstReg).addReg(SrcReg);
1670
1671     // Mark the register as live out of the function.
1672     MRI.addLiveOut(VA.getLocReg());
1673   }
1674
1675   unsigned RetOpc = isThumb ? ARM::tBX_RET : ARM::BX_RET;
1676   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1677                           TII.get(RetOpc)));
1678   return true;
1679 }
1680
1681 // A quick function that will emit a call for a named libcall in F with the
1682 // vector of passed arguments for the Instruction in I. We can assume that we
1683 // can emit a call for any libcall we can produce. This is an abridged version
1684 // of the full call infrastructure since we won't need to worry about things
1685 // like computed function pointers or strange arguments at call sites.
1686 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
1687 // with X86.
1688 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
1689   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
1690
1691   // Handle *simple* calls for now.
1692   const Type *RetTy = I->getType();
1693   MVT RetVT;
1694   if (RetTy->isVoidTy())
1695     RetVT = MVT::isVoid;
1696   else if (!isTypeLegal(RetTy, RetVT))
1697     return false;
1698
1699   // For now we're using BLX etc on the assumption that we have v5t ops.
1700   if (!Subtarget->hasV5TOps()) return false;
1701
1702   // Set up the argument vectors.
1703   SmallVector<Value*, 8> Args;
1704   SmallVector<unsigned, 8> ArgRegs;
1705   SmallVector<MVT, 8> ArgVTs;
1706   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1707   Args.reserve(I->getNumOperands());
1708   ArgRegs.reserve(I->getNumOperands());
1709   ArgVTs.reserve(I->getNumOperands());
1710   ArgFlags.reserve(I->getNumOperands());
1711   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1712     Value *Op = I->getOperand(i);
1713     unsigned Arg = getRegForValue(Op);
1714     if (Arg == 0) return false;
1715
1716     const Type *ArgTy = Op->getType();
1717     MVT ArgVT;
1718     if (!isTypeLegal(ArgTy, ArgVT)) return false;
1719
1720     ISD::ArgFlagsTy Flags;
1721     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1722     Flags.setOrigAlign(OriginalAlignment);
1723
1724     Args.push_back(Op);
1725     ArgRegs.push_back(Arg);
1726     ArgVTs.push_back(ArgVT);
1727     ArgFlags.push_back(Flags);
1728   }
1729
1730   // Handle the arguments now that we've gotten them.
1731   SmallVector<unsigned, 4> RegArgs;
1732   unsigned NumBytes;
1733   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1734     return false;
1735
1736   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1737   // TODO: Turn this into the table of arm call ops.
1738   MachineInstrBuilder MIB;
1739   unsigned CallOpc;
1740   if(isThumb)
1741     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1742   else
1743     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1744   // Explicitly adding the predicate here.
1745   MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1746                        TII.get(CallOpc)))
1747         .addExternalSymbol(TLI.getLibcallName(Call));
1748
1749   // Add implicit physical register uses to the call.
1750   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1751     MIB.addReg(RegArgs[i]);
1752
1753   // Finish off the call including any return values.
1754   SmallVector<unsigned, 4> UsedRegs;
1755   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1756
1757   // Set all unused physreg defs as dead.
1758   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1759
1760   return true;
1761 }
1762
1763 bool ARMFastISel::SelectCall(const Instruction *I) {
1764   const CallInst *CI = cast<CallInst>(I);
1765   const Value *Callee = CI->getCalledValue();
1766
1767   // Can't handle inline asm or worry about intrinsics yet.
1768   if (isa<InlineAsm>(Callee) || isa<IntrinsicInst>(CI)) return false;
1769
1770   // Only handle global variable Callees that are direct calls.
1771   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1772   if (!GV || Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel()))
1773     return false;
1774
1775   // Check the calling convention.
1776   ImmutableCallSite CS(CI);
1777   CallingConv::ID CC = CS.getCallingConv();
1778
1779   // TODO: Avoid some calling conventions?
1780
1781   // Let SDISel handle vararg functions.
1782   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1783   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1784   if (FTy->isVarArg())
1785     return false;
1786
1787   // Handle *simple* calls for now.
1788   const Type *RetTy = I->getType();
1789   MVT RetVT;
1790   if (RetTy->isVoidTy())
1791     RetVT = MVT::isVoid;
1792   else if (!isTypeLegal(RetTy, RetVT))
1793     return false;
1794
1795   // For now we're using BLX etc on the assumption that we have v5t ops.
1796   // TODO: Maybe?
1797   if (!Subtarget->hasV5TOps()) return false;
1798
1799   // Set up the argument vectors.
1800   SmallVector<Value*, 8> Args;
1801   SmallVector<unsigned, 8> ArgRegs;
1802   SmallVector<MVT, 8> ArgVTs;
1803   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1804   Args.reserve(CS.arg_size());
1805   ArgRegs.reserve(CS.arg_size());
1806   ArgVTs.reserve(CS.arg_size());
1807   ArgFlags.reserve(CS.arg_size());
1808   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1809        i != e; ++i) {
1810     unsigned Arg = getRegForValue(*i);
1811
1812     if (Arg == 0)
1813       return false;
1814     ISD::ArgFlagsTy Flags;
1815     unsigned AttrInd = i - CS.arg_begin() + 1;
1816     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1817       Flags.setSExt();
1818     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1819       Flags.setZExt();
1820
1821          // FIXME: Only handle *easy* calls for now.
1822     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1823         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1824         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1825         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1826       return false;
1827
1828     const Type *ArgTy = (*i)->getType();
1829     MVT ArgVT;
1830     if (!isTypeLegal(ArgTy, ArgVT))
1831       return false;
1832     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1833     Flags.setOrigAlign(OriginalAlignment);
1834
1835     Args.push_back(*i);
1836     ArgRegs.push_back(Arg);
1837     ArgVTs.push_back(ArgVT);
1838     ArgFlags.push_back(Flags);
1839   }
1840
1841   // Handle the arguments now that we've gotten them.
1842   SmallVector<unsigned, 4> RegArgs;
1843   unsigned NumBytes;
1844   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1845     return false;
1846
1847   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1848   // TODO: Turn this into the table of arm call ops.
1849   MachineInstrBuilder MIB;
1850   unsigned CallOpc;
1851   if(isThumb)
1852     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1853   else
1854     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1855   // Explicitly adding the predicate here.
1856   MIB = AddDefaultPred(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1857                                TII.get(CallOpc)))
1858         .addGlobalAddress(GV, 0, 0);
1859
1860   // Add implicit physical register uses to the call.
1861   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1862     MIB.addReg(RegArgs[i]);
1863
1864   // Finish off the call including any return values.
1865   SmallVector<unsigned, 4> UsedRegs;
1866   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1867
1868   // Set all unused physreg defs as dead.
1869   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1870
1871   return true;
1872
1873 }
1874
1875 // TODO: SoftFP support.
1876 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
1877
1878   switch (I->getOpcode()) {
1879     case Instruction::Load:
1880       return SelectLoad(I);
1881     case Instruction::Store:
1882       return SelectStore(I);
1883     case Instruction::Br:
1884       return SelectBranch(I);
1885     case Instruction::ICmp:
1886     case Instruction::FCmp:
1887       return SelectCmp(I);
1888     case Instruction::FPExt:
1889       return SelectFPExt(I);
1890     case Instruction::FPTrunc:
1891       return SelectFPTrunc(I);
1892     case Instruction::SIToFP:
1893       return SelectSIToFP(I);
1894     case Instruction::FPToSI:
1895       return SelectFPToSI(I);
1896     case Instruction::FAdd:
1897       return SelectBinaryOp(I, ISD::FADD);
1898     case Instruction::FSub:
1899       return SelectBinaryOp(I, ISD::FSUB);
1900     case Instruction::FMul:
1901       return SelectBinaryOp(I, ISD::FMUL);
1902     case Instruction::SDiv:
1903       return SelectSDiv(I);
1904     case Instruction::SRem:
1905       return SelectSRem(I);
1906     case Instruction::Call:
1907       return SelectCall(I);
1908     case Instruction::Select:
1909       return SelectSelect(I);
1910     case Instruction::Ret:
1911       return SelectRet(I);
1912     default: break;
1913   }
1914   return false;
1915 }
1916
1917 namespace llvm {
1918   llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
1919     // Completely untested on non-darwin.
1920     const TargetMachine &TM = funcInfo.MF->getTarget();
1921
1922     // Darwin and thumb1 only for now.
1923     const ARMSubtarget *Subtarget = &TM.getSubtarget<ARMSubtarget>();
1924     if (Subtarget->isTargetDarwin() && !Subtarget->isThumb1Only() &&
1925         !DisableARMFastISel)
1926       return new ARMFastISel(funcInfo);
1927     return 0;
1928   }
1929 }