Implement select handling for ARM fast-isel.
[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/MachineRegisterInfo.h"
37 #include "llvm/Support/CallSite.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/ErrorHandling.h"
40 #include "llvm/Support/GetElementPtrTypeIterator.h"
41 #include "llvm/Target/TargetData.h"
42 #include "llvm/Target/TargetInstrInfo.h"
43 #include "llvm/Target/TargetLowering.h"
44 #include "llvm/Target/TargetMachine.h"
45 #include "llvm/Target/TargetOptions.h"
46 using namespace llvm;
47
48 static cl::opt<bool>
49 EnableARMFastISel("arm-fast-isel",
50                   cl::desc("Turn on experimental ARM fast-isel support"),
51                   cl::init(false), cl::Hidden);
52
53 namespace {
54
55 class ARMFastISel : public FastISel {
56
57   /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
58   /// make the right decision when generating code for different targets.
59   const ARMSubtarget *Subtarget;
60   const TargetMachine &TM;
61   const TargetInstrInfo &TII;
62   const TargetLowering &TLI;
63   ARMFunctionInfo *AFI;
64
65   // Convenience variables to avoid some queries.
66   bool isThumb;
67   LLVMContext *Context;
68
69   public:
70     explicit ARMFastISel(FunctionLoweringInfo &funcInfo)
71     : FastISel(funcInfo),
72       TM(funcInfo.MF->getTarget()),
73       TII(*TM.getInstrInfo()),
74       TLI(*TM.getTargetLowering()) {
75       Subtarget = &TM.getSubtarget<ARMSubtarget>();
76       AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
77       isThumb = AFI->isThumbFunction();
78       Context = &funcInfo.Fn->getContext();
79     }
80
81     // Code from FastISel.cpp.
82     virtual unsigned FastEmitInst_(unsigned MachineInstOpcode,
83                                    const TargetRegisterClass *RC);
84     virtual unsigned FastEmitInst_r(unsigned MachineInstOpcode,
85                                     const TargetRegisterClass *RC,
86                                     unsigned Op0, bool Op0IsKill);
87     virtual unsigned FastEmitInst_rr(unsigned MachineInstOpcode,
88                                      const TargetRegisterClass *RC,
89                                      unsigned Op0, bool Op0IsKill,
90                                      unsigned Op1, bool Op1IsKill);
91     virtual unsigned FastEmitInst_ri(unsigned MachineInstOpcode,
92                                      const TargetRegisterClass *RC,
93                                      unsigned Op0, bool Op0IsKill,
94                                      uint64_t Imm);
95     virtual unsigned FastEmitInst_rf(unsigned MachineInstOpcode,
96                                      const TargetRegisterClass *RC,
97                                      unsigned Op0, bool Op0IsKill,
98                                      const ConstantFP *FPImm);
99     virtual unsigned FastEmitInst_i(unsigned MachineInstOpcode,
100                                     const TargetRegisterClass *RC,
101                                     uint64_t Imm);
102     virtual unsigned FastEmitInst_rri(unsigned MachineInstOpcode,
103                                       const TargetRegisterClass *RC,
104                                       unsigned Op0, bool Op0IsKill,
105                                       unsigned Op1, bool Op1IsKill,
106                                       uint64_t Imm);
107     virtual unsigned FastEmitInst_extractsubreg(MVT RetVT,
108                                                 unsigned Op0, bool Op0IsKill,
109                                                 uint32_t Idx);
110
111     // Backend specific FastISel code.
112     virtual bool TargetSelectInstruction(const Instruction *I);
113     virtual unsigned TargetMaterializeConstant(const Constant *C);
114     virtual unsigned TargetMaterializeAlloca(const AllocaInst *AI);
115
116   #include "ARMGenFastISel.inc"
117
118     // Instruction selection routines.
119   private:
120     virtual bool SelectLoad(const Instruction *I);
121     virtual bool SelectStore(const Instruction *I);
122     virtual bool SelectBranch(const Instruction *I);
123     virtual bool SelectCmp(const Instruction *I);
124     virtual bool SelectFPExt(const Instruction *I);
125     virtual bool SelectFPTrunc(const Instruction *I);
126     virtual bool SelectBinaryOp(const Instruction *I, unsigned ISDOpcode);
127     virtual bool SelectSIToFP(const Instruction *I);
128     virtual bool SelectFPToSI(const Instruction *I);
129     virtual bool SelectSDiv(const Instruction *I);
130     virtual bool SelectCall(const Instruction *I);
131     virtual bool SelectSelect(const Instruction *I);
132
133     // Utility routines.
134   private:
135     bool isTypeLegal(const Type *Ty, EVT &VT);
136     bool isLoadTypeLegal(const Type *Ty, EVT &VT);
137     bool ARMEmitLoad(EVT VT, unsigned &ResultReg, unsigned Reg, int Offset);
138     bool ARMEmitStore(EVT VT, unsigned SrcReg, unsigned Reg, int Offset);
139     bool ARMLoadAlloca(const Instruction *I, EVT VT);
140     bool ARMStoreAlloca(const Instruction *I, unsigned SrcReg, EVT VT);
141     bool ARMComputeRegOffset(const Value *Obj, unsigned &Reg, int &Offset);
142     unsigned ARMMaterializeFP(const ConstantFP *CFP, EVT VT);
143     unsigned ARMMaterializeInt(const Constant *C, EVT VT);
144     unsigned ARMMaterializeGV(const GlobalValue *GV, EVT VT);
145     unsigned ARMMoveToFPReg(EVT VT, unsigned SrcReg);
146     unsigned ARMMoveToIntReg(EVT VT, unsigned SrcReg);
147
148     // Call handling routines.
149   private:
150     CCAssignFn *CCAssignFnForCall(CallingConv::ID CC, bool Return);
151     bool ProcessCallArgs(SmallVectorImpl<Value*> &Args, 
152                          SmallVectorImpl<unsigned> &ArgRegs,
153                          SmallVectorImpl<EVT> &ArgVTs,
154                          SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
155                          SmallVectorImpl<unsigned> &RegArgs,
156                          CallingConv::ID CC,
157                          unsigned &NumBytes);
158     bool FinishCall(EVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
159                     const Instruction *I, CallingConv::ID CC,
160                     unsigned &NumBytes);
161     bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
162
163     // OptionalDef handling routines.
164   private:
165     bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
166     const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
167 };
168
169 } // end anonymous namespace
170
171 #include "ARMGenCallingConv.inc"
172
173 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
174 // we don't care about implicit defs here, just places we'll need to add a
175 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
176 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
177   const TargetInstrDesc &TID = MI->getDesc();
178   if (!TID.hasOptionalDef())
179     return false;
180
181   // Look to see if our OptionalDef is defining CPSR or CCR.
182   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
183     const MachineOperand &MO = MI->getOperand(i);
184     if (!MO.isReg() || !MO.isDef()) continue;
185     if (MO.getReg() == ARM::CPSR)
186       *CPSR = true;
187   }
188   return true;
189 }
190
191 // If the machine is predicable go ahead and add the predicate operands, if
192 // it needs default CC operands add those.
193 const MachineInstrBuilder &
194 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
195   MachineInstr *MI = &*MIB;
196
197   // Do we use a predicate?
198   if (TII.isPredicable(MI))
199     AddDefaultPred(MIB);
200
201   // Do we optionally set a predicate?  Preds is size > 0 iff the predicate
202   // defines CPSR. All other OptionalDefines in ARM are the CCR register.
203   bool CPSR = false;
204   if (DefinesOptionalPredicate(MI, &CPSR)) {
205     if (CPSR)
206       AddDefaultT1CC(MIB);
207     else
208       AddDefaultCC(MIB);
209   }
210   return MIB;
211 }
212
213 unsigned ARMFastISel::FastEmitInst_(unsigned MachineInstOpcode,
214                                     const TargetRegisterClass* RC) {
215   unsigned ResultReg = createResultReg(RC);
216   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
217
218   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg));
219   return ResultReg;
220 }
221
222 unsigned ARMFastISel::FastEmitInst_r(unsigned MachineInstOpcode,
223                                      const TargetRegisterClass *RC,
224                                      unsigned Op0, bool Op0IsKill) {
225   unsigned ResultReg = createResultReg(RC);
226   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
227
228   if (II.getNumDefs() >= 1)
229     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
230                    .addReg(Op0, Op0IsKill * RegState::Kill));
231   else {
232     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
233                    .addReg(Op0, Op0IsKill * RegState::Kill));
234     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
235                    TII.get(TargetOpcode::COPY), ResultReg)
236                    .addReg(II.ImplicitDefs[0]));
237   }
238   return ResultReg;
239 }
240
241 unsigned ARMFastISel::FastEmitInst_rr(unsigned MachineInstOpcode,
242                                       const TargetRegisterClass *RC,
243                                       unsigned Op0, bool Op0IsKill,
244                                       unsigned Op1, bool Op1IsKill) {
245   unsigned ResultReg = createResultReg(RC);
246   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
247
248   if (II.getNumDefs() >= 1)
249     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
250                    .addReg(Op0, Op0IsKill * RegState::Kill)
251                    .addReg(Op1, Op1IsKill * RegState::Kill));
252   else {
253     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
254                    .addReg(Op0, Op0IsKill * RegState::Kill)
255                    .addReg(Op1, Op1IsKill * RegState::Kill));
256     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
257                            TII.get(TargetOpcode::COPY), ResultReg)
258                    .addReg(II.ImplicitDefs[0]));
259   }
260   return ResultReg;
261 }
262
263 unsigned ARMFastISel::FastEmitInst_ri(unsigned MachineInstOpcode,
264                                       const TargetRegisterClass *RC,
265                                       unsigned Op0, bool Op0IsKill,
266                                       uint64_t Imm) {
267   unsigned ResultReg = createResultReg(RC);
268   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
269
270   if (II.getNumDefs() >= 1)
271     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
272                    .addReg(Op0, Op0IsKill * RegState::Kill)
273                    .addImm(Imm));
274   else {
275     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
276                    .addReg(Op0, Op0IsKill * RegState::Kill)
277                    .addImm(Imm));
278     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
279                            TII.get(TargetOpcode::COPY), ResultReg)
280                    .addReg(II.ImplicitDefs[0]));
281   }
282   return ResultReg;
283 }
284
285 unsigned ARMFastISel::FastEmitInst_rf(unsigned MachineInstOpcode,
286                                       const TargetRegisterClass *RC,
287                                       unsigned Op0, bool Op0IsKill,
288                                       const ConstantFP *FPImm) {
289   unsigned ResultReg = createResultReg(RC);
290   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
291
292   if (II.getNumDefs() >= 1)
293     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
294                    .addReg(Op0, Op0IsKill * RegState::Kill)
295                    .addFPImm(FPImm));
296   else {
297     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
298                    .addReg(Op0, Op0IsKill * RegState::Kill)
299                    .addFPImm(FPImm));
300     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
301                            TII.get(TargetOpcode::COPY), ResultReg)
302                    .addReg(II.ImplicitDefs[0]));
303   }
304   return ResultReg;
305 }
306
307 unsigned ARMFastISel::FastEmitInst_rri(unsigned MachineInstOpcode,
308                                        const TargetRegisterClass *RC,
309                                        unsigned Op0, bool Op0IsKill,
310                                        unsigned Op1, bool Op1IsKill,
311                                        uint64_t Imm) {
312   unsigned ResultReg = createResultReg(RC);
313   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
314
315   if (II.getNumDefs() >= 1)
316     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
317                    .addReg(Op0, Op0IsKill * RegState::Kill)
318                    .addReg(Op1, Op1IsKill * RegState::Kill)
319                    .addImm(Imm));
320   else {
321     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
322                    .addReg(Op0, Op0IsKill * RegState::Kill)
323                    .addReg(Op1, Op1IsKill * RegState::Kill)
324                    .addImm(Imm));
325     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
326                            TII.get(TargetOpcode::COPY), ResultReg)
327                    .addReg(II.ImplicitDefs[0]));
328   }
329   return ResultReg;
330 }
331
332 unsigned ARMFastISel::FastEmitInst_i(unsigned MachineInstOpcode,
333                                      const TargetRegisterClass *RC,
334                                      uint64_t Imm) {
335   unsigned ResultReg = createResultReg(RC);
336   const TargetInstrDesc &II = TII.get(MachineInstOpcode);
337
338   if (II.getNumDefs() >= 1)
339     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II, ResultReg)
340                    .addImm(Imm));
341   else {
342     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, II)
343                    .addImm(Imm));
344     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
345                            TII.get(TargetOpcode::COPY), ResultReg)
346                    .addReg(II.ImplicitDefs[0]));
347   }
348   return ResultReg;
349 }
350
351 unsigned ARMFastISel::FastEmitInst_extractsubreg(MVT RetVT,
352                                                  unsigned Op0, bool Op0IsKill,
353                                                  uint32_t Idx) {
354   unsigned ResultReg = createResultReg(TLI.getRegClassFor(RetVT));
355   assert(TargetRegisterInfo::isVirtualRegister(Op0) &&
356          "Cannot yet extract from physregs");
357   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
358                          DL, TII.get(TargetOpcode::COPY), ResultReg)
359                  .addReg(Op0, getKillRegState(Op0IsKill), Idx));
360   return ResultReg;
361 }
362
363 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
364 // checks from the various callers.
365 unsigned ARMFastISel::ARMMoveToFPReg(EVT VT, unsigned SrcReg) {
366   if (VT.getSimpleVT().SimpleTy == MVT::f64) return 0;
367   
368   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
369   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
370                           TII.get(ARM::VMOVRS), MoveReg)
371                   .addReg(SrcReg));
372   return MoveReg;
373 }
374
375 unsigned ARMFastISel::ARMMoveToIntReg(EVT VT, unsigned SrcReg) {
376   if (VT.getSimpleVT().SimpleTy == MVT::i64) return 0;
377   
378   unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
379   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
380                           TII.get(ARM::VMOVSR), MoveReg)
381                   .addReg(SrcReg));
382   return MoveReg;
383 }
384
385 // For double width floating point we need to materialize two constants
386 // (the high and the low) into integer registers then use a move to get
387 // the combined constant into an FP reg.
388 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, EVT VT) {
389   const APFloat Val = CFP->getValueAPF();
390   bool is64bit = VT.getSimpleVT().SimpleTy == MVT::f64;
391
392   // This checks to see if we can use VFP3 instructions to materialize
393   // a constant, otherwise we have to go through the constant pool.
394   if (TLI.isFPImmLegal(Val, VT)) {
395     unsigned Opc = is64bit ? ARM::FCONSTD : ARM::FCONSTS;
396     unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
397     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
398                             DestReg)
399                     .addFPImm(CFP));
400     return DestReg;
401   }
402   
403   // Require VFP2 for loading fp constants.
404   if (!Subtarget->hasVFP2()) return false;
405   
406   // MachineConstantPool wants an explicit alignment.
407   unsigned Align = TD.getPrefTypeAlignment(CFP->getType());
408   if (Align == 0) {
409     // TODO: Figure out if this is correct.
410     Align = TD.getTypeAllocSize(CFP->getType());
411   }
412   unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
413   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
414   unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
415   
416   // The extra reg is for addrmode5.
417   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
418                           DestReg)
419                   .addConstantPoolIndex(Idx)
420                   .addReg(0));
421   return DestReg;
422 }
423
424 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, EVT VT) {
425   
426   // For now 32-bit only.
427   if (VT.getSimpleVT().SimpleTy != MVT::i32) return false;
428   
429   // MachineConstantPool wants an explicit alignment.
430   unsigned Align = TD.getPrefTypeAlignment(C->getType());
431   if (Align == 0) {
432     // TODO: Figure out if this is correct.
433     Align = TD.getTypeAllocSize(C->getType());
434   }
435   unsigned Idx = MCP.getConstantPoolIndex(C, Align);
436   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
437   
438   if (isThumb)
439     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
440                             TII.get(ARM::t2LDRpci), DestReg)
441                     .addConstantPoolIndex(Idx));
442   else
443     // The extra reg and immediate are for addrmode2.
444     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
445                             TII.get(ARM::LDRcp), DestReg)
446                     .addConstantPoolIndex(Idx)
447                     .addReg(0).addImm(0));
448
449   return DestReg;
450 }
451
452 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, EVT VT) {
453   // For now 32-bit only.
454   if (VT.getSimpleVT().SimpleTy != MVT::i32) return 0;
455   
456   Reloc::Model RelocM = TM.getRelocationModel();
457   
458   // TODO: No external globals for now.
459   if (Subtarget->GVIsIndirectSymbol(GV, RelocM)) return 0;
460   
461   // TODO: Need more magic for ARM PIC.
462   if (!isThumb && (RelocM == Reloc::PIC_)) return 0;
463   
464   // MachineConstantPool wants an explicit alignment.
465   unsigned Align = TD.getPrefTypeAlignment(GV->getType());
466   if (Align == 0) {
467     // TODO: Figure out if this is correct.
468     Align = TD.getTypeAllocSize(GV->getType());
469   }
470   
471   // Grab index.
472   unsigned PCAdj = (RelocM != Reloc::PIC_) ? 0 : (Subtarget->isThumb() ? 4 : 8);
473   unsigned Id = AFI->createConstPoolEntryUId();
474   ARMConstantPoolValue *CPV = new ARMConstantPoolValue(GV, Id,
475                                                        ARMCP::CPValue, PCAdj);
476   unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
477   
478   // Load value.
479   MachineInstrBuilder MIB;
480   unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
481   if (isThumb) {
482     unsigned Opc = (RelocM != Reloc::PIC_) ? ARM::t2LDRpci : ARM::t2LDRpci_pic;
483     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc), DestReg)
484           .addConstantPoolIndex(Idx);
485     if (RelocM == Reloc::PIC_)
486       MIB.addImm(Id);
487   } else {
488     // The extra reg and immediate are for addrmode2.
489     MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(ARM::LDRcp),
490                   DestReg)
491           .addConstantPoolIndex(Idx)
492           .addReg(0).addImm(0);
493   }
494   AddOptionalDefs(MIB);
495   return DestReg;
496 }
497
498 unsigned ARMFastISel::TargetMaterializeConstant(const Constant *C) {
499   EVT VT = TLI.getValueType(C->getType(), true);
500
501   // Only handle simple types.
502   if (!VT.isSimple()) return 0;
503
504   if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
505     return ARMMaterializeFP(CFP, VT);
506   else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
507     return ARMMaterializeGV(GV, VT);
508   else if (isa<ConstantInt>(C))
509     return ARMMaterializeInt(C, VT);
510   
511   return 0;
512 }
513
514 unsigned ARMFastISel::TargetMaterializeAlloca(const AllocaInst *AI) {
515   // Don't handle dynamic allocas.
516   if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
517   
518   EVT VT;
519   if (!isTypeLegal(AI->getType(), VT)) return false;
520   
521   DenseMap<const AllocaInst*, int>::iterator SI =
522     FuncInfo.StaticAllocaMap.find(AI);
523
524   // This will get lowered later into the correct offsets and registers
525   // via rewriteXFrameIndex.
526   if (SI != FuncInfo.StaticAllocaMap.end()) {
527     TargetRegisterClass* RC = TLI.getRegClassFor(VT);
528     unsigned ResultReg = createResultReg(RC);
529     unsigned Opc = isThumb ? ARM::t2ADDri : ARM::ADDri;
530     AddOptionalDefs(BuildMI(*FuncInfo.MBB, *FuncInfo.InsertPt, DL,
531                             TII.get(Opc), ResultReg)
532                             .addFrameIndex(SI->second)
533                             .addImm(0));
534     return ResultReg;
535   }
536   
537   return 0;
538 }
539
540 bool ARMFastISel::isTypeLegal(const Type *Ty, EVT &VT) {
541   VT = TLI.getValueType(Ty, true);
542
543   // Only handle simple types.
544   if (VT == MVT::Other || !VT.isSimple()) return false;
545
546   // Handle all legal types, i.e. a register that will directly hold this
547   // value.
548   return TLI.isTypeLegal(VT);
549 }
550
551 bool ARMFastISel::isLoadTypeLegal(const Type *Ty, EVT &VT) {
552   if (isTypeLegal(Ty, VT)) return true;
553
554   // If this is a type than can be sign or zero-extended to a basic operation
555   // go ahead and accept it now.
556   if (VT == MVT::i8 || VT == MVT::i16)
557     return true;
558
559   return false;
560 }
561
562 // Computes the Reg+Offset to get to an object.
563 bool ARMFastISel::ARMComputeRegOffset(const Value *Obj, unsigned &Reg,
564                                       int &Offset) {
565   // Some boilerplate from the X86 FastISel.
566   const User *U = NULL;
567   unsigned Opcode = Instruction::UserOp1;
568   if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
569     // Don't walk into other basic blocks; it's possible we haven't
570     // visited them yet, so the instructions may not yet be assigned
571     // virtual registers.
572     if (FuncInfo.MBBMap[I->getParent()] != FuncInfo.MBB)
573       return false;
574     Opcode = I->getOpcode();
575     U = I;
576   } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
577     Opcode = C->getOpcode();
578     U = C;
579   }
580
581   if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
582     if (Ty->getAddressSpace() > 255)
583       // Fast instruction selection doesn't support the special
584       // address spaces.
585       return false;
586
587   switch (Opcode) {
588     default:
589     break;
590     case Instruction::Alloca: {
591       assert(false && "Alloca should have been handled earlier!");
592       return false;
593     }
594   }
595
596   // FIXME: Handle global variables.
597   if (const GlobalValue *GV = dyn_cast<GlobalValue>(Obj)) {
598     (void)GV;
599     return false;
600   }
601
602   // Try to get this in a register if nothing else has worked.
603   Reg = getRegForValue(Obj);
604   if (Reg == 0) return false;
605
606   // Since the offset may be too large for the load instruction
607   // get the reg+offset into a register.
608   // TODO: Verify the additions work, otherwise we'll need to add the
609   // offset instead of 0 to the instructions and do all sorts of operand
610   // munging.
611   // TODO: Optimize this somewhat.
612   if (Offset != 0) {
613     ARMCC::CondCodes Pred = ARMCC::AL;
614     unsigned PredReg = 0;
615
616     if (!isThumb)
617       emitARMRegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
618                               Reg, Reg, Offset, Pred, PredReg,
619                               static_cast<const ARMBaseInstrInfo&>(TII));
620     else {
621       assert(AFI->isThumb2Function());
622       emitT2RegPlusImmediate(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
623                              Reg, Reg, Offset, Pred, PredReg,
624                              static_cast<const ARMBaseInstrInfo&>(TII));
625     }
626   }
627   return true;
628 }
629
630 bool ARMFastISel::ARMLoadAlloca(const Instruction *I, EVT VT) {
631   Value *Op0 = I->getOperand(0);
632
633   // Promote load/store types.
634   if (VT == MVT::i8 || VT == MVT::i16) VT = MVT::i32;
635
636   // Verify it's an alloca.
637   if (const AllocaInst *AI = dyn_cast<AllocaInst>(Op0)) {
638     DenseMap<const AllocaInst*, int>::iterator SI =
639       FuncInfo.StaticAllocaMap.find(AI);
640
641     if (SI != FuncInfo.StaticAllocaMap.end()) {
642       TargetRegisterClass* RC = TLI.getRegClassFor(VT);
643       unsigned ResultReg = createResultReg(RC);
644       TII.loadRegFromStackSlot(*FuncInfo.MBB, *FuncInfo.InsertPt,
645                                ResultReg, SI->second, RC,
646                                TM.getRegisterInfo());
647       UpdateValueMap(I, ResultReg);
648       return true;
649     }
650   }
651   return false;
652 }
653
654 bool ARMFastISel::ARMEmitLoad(EVT VT, unsigned &ResultReg,
655                               unsigned Reg, int Offset) {
656
657   assert(VT.isSimple() && "Non-simple types are invalid here!");
658   unsigned Opc;
659   TargetRegisterClass *RC;
660   bool isFloat = false;
661   switch (VT.getSimpleVT().SimpleTy) {
662     default:
663       // This is mostly going to be Neon/vector support.
664       return false;
665     case MVT::i16:
666       Opc = isThumb ? ARM::t2LDRHi8 : ARM::LDRH;
667       RC = ARM::GPRRegisterClass;
668       VT = MVT::i32;
669       break;
670     case MVT::i8:
671       Opc = isThumb ? ARM::t2LDRBi8 : ARM::LDRB;
672       RC = ARM::GPRRegisterClass;
673       VT = MVT::i32;
674       break;
675     case MVT::i32:
676       Opc = isThumb ? ARM::t2LDRi8 : ARM::LDR;
677       RC = ARM::GPRRegisterClass;
678       break;
679     case MVT::f32:
680       Opc = ARM::VLDRS;
681       RC = TLI.getRegClassFor(VT);
682       isFloat = true;
683       break;
684     case MVT::f64:
685       Opc = ARM::VLDRD;
686       RC = TLI.getRegClassFor(VT);
687       isFloat = true;
688       break;
689   }
690
691   ResultReg = createResultReg(RC);
692
693   // For now with the additions above the offset should be zero - thus we
694   // can always fit into an i8.
695   assert(Offset == 0 && "Offset not zero!");
696   
697   // The thumb and floating point instructions both take 2 operands, ARM takes
698   // another register.
699   if (isFloat || isThumb)
700     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
701                             TII.get(Opc), ResultReg)
702                     .addReg(Reg).addImm(Offset));
703   else
704     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
705                             TII.get(Opc), ResultReg)
706                     .addReg(Reg).addReg(0).addImm(Offset));
707   return true;
708 }
709
710 bool ARMFastISel::SelectLoad(const Instruction *I) {
711   // Verify we have a legal type before going any further.
712   EVT VT;
713   if (!isLoadTypeLegal(I->getType(), VT))
714     return false;
715
716   // If we're an alloca we know we have a frame index and can emit the load
717   // directly in short order.
718   if (ARMLoadAlloca(I, VT))
719     return true;
720
721   // Our register and offset with innocuous defaults.
722   unsigned Reg = 0;
723   int Offset = 0;
724
725   // See if we can handle this as Reg + Offset
726   if (!ARMComputeRegOffset(I->getOperand(0), Reg, Offset))
727     return false;
728
729   unsigned ResultReg;
730   if (!ARMEmitLoad(VT, ResultReg, Reg, Offset /* 0 */)) return false;
731
732   UpdateValueMap(I, ResultReg);
733   return true;
734 }
735
736 bool ARMFastISel::ARMStoreAlloca(const Instruction *I, unsigned SrcReg, EVT VT){
737   Value *Op1 = I->getOperand(1);
738
739   // Promote load/store types.
740   if (VT == MVT::i8 || VT == MVT::i16) VT = MVT::i32;
741
742   // Verify it's an alloca.
743   if (const AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
744     DenseMap<const AllocaInst*, int>::iterator SI =
745       FuncInfo.StaticAllocaMap.find(AI);
746
747     if (SI != FuncInfo.StaticAllocaMap.end()) {
748       TargetRegisterClass* RC = TLI.getRegClassFor(VT);
749       assert(SrcReg != 0 && "Nothing to store!");
750       TII.storeRegToStackSlot(*FuncInfo.MBB, *FuncInfo.InsertPt,
751                               SrcReg, true /*isKill*/, SI->second, RC,
752                               TM.getRegisterInfo());
753       return true;
754     }
755   }
756   return false;
757 }
758
759 bool ARMFastISel::ARMEmitStore(EVT VT, unsigned SrcReg,
760                                unsigned DstReg, int Offset) {
761   unsigned StrOpc;
762   bool isFloat = false;
763   switch (VT.getSimpleVT().SimpleTy) {
764     default: return false;
765     case MVT::i1:
766     case MVT::i8: StrOpc = isThumb ? ARM::t2STRBi8 : ARM::STRB; break;
767     case MVT::i16: StrOpc = isThumb ? ARM::t2STRHi8 : ARM::STRH; break;
768     case MVT::i32: StrOpc = isThumb ? ARM::t2STRi8 : ARM::STR; break;
769     case MVT::f32:
770       if (!Subtarget->hasVFP2()) return false;
771       StrOpc = ARM::VSTRS;
772       isFloat = true;
773       break;
774     case MVT::f64:
775       if (!Subtarget->hasVFP2()) return false;
776       StrOpc = ARM::VSTRD;
777       isFloat = true;
778       break;
779   }
780
781   // The thumb addressing mode has operands swapped from the arm addressing
782   // mode, the floating point one only has two operands.
783   if (isFloat || isThumb)
784     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
785                             TII.get(StrOpc))
786                     .addReg(SrcReg).addReg(DstReg).addImm(Offset));
787   else
788     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
789                             TII.get(StrOpc))
790                     .addReg(SrcReg).addReg(DstReg).addReg(0).addImm(Offset));
791
792   return true;
793 }
794
795 bool ARMFastISel::SelectStore(const Instruction *I) {
796   Value *Op0 = I->getOperand(0);
797   unsigned SrcReg = 0;
798
799   // Yay type legalization
800   EVT VT;
801   if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
802     return false;
803
804   // Get the value to be stored into a register.
805   SrcReg = getRegForValue(Op0);
806   if (SrcReg == 0)
807     return false;
808
809   // If we're an alloca we know we have a frame index and can emit the store
810   // quickly.
811   if (ARMStoreAlloca(I, SrcReg, VT))
812     return true;
813
814   // Our register and offset with innocuous defaults.
815   unsigned Reg = 0;
816   int Offset = 0;
817
818   // See if we can handle this as Reg + Offset
819   if (!ARMComputeRegOffset(I->getOperand(1), Reg, Offset))
820     return false;
821
822   if (!ARMEmitStore(VT, SrcReg, Reg, Offset /* 0 */)) return false;
823
824   return true;
825 }
826
827 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
828   switch (Pred) {
829     // Needs two compares...
830     case CmpInst::FCMP_ONE:
831     case CmpInst::FCMP_UEQ:    
832     default:
833       assert(false && "Unhandled CmpInst::Predicate!");
834       return ARMCC::AL;
835     case CmpInst::ICMP_EQ:
836     case CmpInst::FCMP_OEQ:
837       return ARMCC::EQ;
838     case CmpInst::ICMP_SGT:
839     case CmpInst::FCMP_OGT:
840       return ARMCC::GT;
841     case CmpInst::ICMP_SGE:
842     case CmpInst::FCMP_OGE:
843       return ARMCC::GE;
844     case CmpInst::ICMP_UGT:
845     case CmpInst::FCMP_UGT:
846       return ARMCC::HI;
847     case CmpInst::FCMP_OLT:
848       return ARMCC::MI;
849     case CmpInst::ICMP_ULE:
850     case CmpInst::FCMP_OLE:
851       return ARMCC::LS;
852     case CmpInst::FCMP_ORD:
853       return ARMCC::VC;
854     case CmpInst::FCMP_UNO:
855       return ARMCC::VS;
856     case CmpInst::FCMP_UGE:
857       return ARMCC::PL;
858     case CmpInst::ICMP_SLT:
859     case CmpInst::FCMP_ULT:
860       return ARMCC::LT;  
861     case CmpInst::ICMP_SLE:
862     case CmpInst::FCMP_ULE:
863       return ARMCC::LE;
864     case CmpInst::FCMP_UNE:
865     case CmpInst::ICMP_NE:
866       return ARMCC::NE;
867     case CmpInst::ICMP_UGE:
868       return ARMCC::HS;
869     case CmpInst::ICMP_ULT:
870       return ARMCC::LO;
871   }
872 }
873
874 bool ARMFastISel::SelectBranch(const Instruction *I) {
875   const BranchInst *BI = cast<BranchInst>(I);
876   MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
877   MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
878
879   // Simple branch support.
880   // TODO: Try to avoid the re-computation in some places.
881   unsigned CondReg = getRegForValue(BI->getCondition());
882   if (CondReg == 0) return false;
883
884   // Re-set the flags just in case.
885   unsigned CmpOpc = isThumb ? ARM::t2CMPri : ARM::CMPri;
886   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
887                   .addReg(CondReg).addImm(1));
888   
889   unsigned BrOpc = isThumb ? ARM::t2Bcc : ARM::Bcc;
890   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(BrOpc))
891                   .addMBB(TBB).addImm(ARMCC::EQ).addReg(ARM::CPSR);
892   FastEmitBranch(FBB, DL);
893   FuncInfo.MBB->addSuccessor(TBB);
894   return true;  
895 }
896
897 bool ARMFastISel::SelectCmp(const Instruction *I) {
898   const CmpInst *CI = cast<CmpInst>(I);
899
900   EVT VT;
901   const Type *Ty = CI->getOperand(0)->getType();
902   if (!isTypeLegal(Ty, VT))
903     return false;
904
905   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
906   if (isFloat && !Subtarget->hasVFP2())
907     return false;
908
909   unsigned CmpOpc;
910   unsigned CondReg;
911   switch (VT.getSimpleVT().SimpleTy) {
912     default: return false;
913     // TODO: Verify compares.
914     case MVT::f32:
915       CmpOpc = ARM::VCMPES;
916       CondReg = ARM::FPSCR;
917       break;
918     case MVT::f64:
919       CmpOpc = ARM::VCMPED;
920       CondReg = ARM::FPSCR;
921       break;
922     case MVT::i32:
923       CmpOpc = isThumb ? ARM::t2CMPrr : ARM::CMPrr;
924       CondReg = ARM::CPSR;
925       break;
926   }
927
928   // Get the compare predicate.
929   ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
930     
931   // We may not handle every CC for now.
932   if (ARMPred == ARMCC::AL) return false;
933
934   unsigned Arg1 = getRegForValue(CI->getOperand(0));
935   if (Arg1 == 0) return false;
936
937   unsigned Arg2 = getRegForValue(CI->getOperand(1));
938   if (Arg2 == 0) return false;
939
940   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
941                   .addReg(Arg1).addReg(Arg2));
942
943   // For floating point we need to move the result to a comparison register
944   // that we can then use for branches.
945   if (isFloat)
946     AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
947                             TII.get(ARM::FMSTAT)));
948
949   // Now set a register based on the comparison. Explicitly set the predicates
950   // here.
951   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCi : ARM::MOVCCi;
952   TargetRegisterClass *RC = isThumb ? ARM::rGPRRegisterClass 
953                                     : ARM::GPRRegisterClass;
954   unsigned DestReg = createResultReg(RC);
955   Constant *Zero 
956     = ConstantInt::get(Type::getInt32Ty(*Context), 0);
957   unsigned ZeroReg = TargetMaterializeConstant(Zero);
958   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), DestReg)
959           .addReg(ZeroReg).addImm(1)
960           .addImm(ARMPred).addReg(CondReg);
961
962   UpdateValueMap(I, DestReg);
963   return true;
964 }
965
966 bool ARMFastISel::SelectFPExt(const Instruction *I) {
967   // Make sure we have VFP and that we're extending float to double.
968   if (!Subtarget->hasVFP2()) return false;
969
970   Value *V = I->getOperand(0);
971   if (!I->getType()->isDoubleTy() ||
972       !V->getType()->isFloatTy()) return false;
973
974   unsigned Op = getRegForValue(V);
975   if (Op == 0) return false;
976
977   unsigned Result = createResultReg(ARM::DPRRegisterClass);
978   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
979                           TII.get(ARM::VCVTDS), Result)
980                   .addReg(Op));
981   UpdateValueMap(I, Result);
982   return true;
983 }
984
985 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
986   // Make sure we have VFP and that we're truncating double to float.
987   if (!Subtarget->hasVFP2()) return false;
988
989   Value *V = I->getOperand(0);
990   if (!(I->getType()->isFloatTy() &&
991         V->getType()->isDoubleTy())) return false;
992
993   unsigned Op = getRegForValue(V);
994   if (Op == 0) return false;
995
996   unsigned Result = createResultReg(ARM::SPRRegisterClass);
997   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
998                           TII.get(ARM::VCVTSD), Result)
999                   .addReg(Op));
1000   UpdateValueMap(I, Result);
1001   return true;
1002 }
1003
1004 bool ARMFastISel::SelectSIToFP(const Instruction *I) {
1005   // Make sure we have VFP.
1006   if (!Subtarget->hasVFP2()) return false;
1007   
1008   EVT DstVT;
1009   const Type *Ty = I->getType();
1010   if (!isTypeLegal(Ty, DstVT))
1011     return false;
1012   
1013   unsigned Op = getRegForValue(I->getOperand(0));
1014   if (Op == 0) return false;
1015   
1016   // The conversion routine works on fp-reg to fp-reg and the operand above
1017   // was an integer, move it to the fp registers if possible.
1018   unsigned FP = ARMMoveToFPReg(MVT::f32, Op);
1019   if (FP == 0) return false;
1020   
1021   unsigned Opc;
1022   if (Ty->isFloatTy()) Opc = ARM::VSITOS;
1023   else if (Ty->isDoubleTy()) Opc = ARM::VSITOD;
1024   else return 0;
1025   
1026   unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1027   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1028                           ResultReg)
1029                   .addReg(FP));
1030   UpdateValueMap(I, ResultReg);
1031   return true;
1032 }
1033
1034 bool ARMFastISel::SelectFPToSI(const Instruction *I) {
1035   // Make sure we have VFP.
1036   if (!Subtarget->hasVFP2()) return false;
1037   
1038   EVT DstVT;
1039   const Type *RetTy = I->getType();
1040   if (!isTypeLegal(RetTy, DstVT))
1041     return false;
1042   
1043   unsigned Op = getRegForValue(I->getOperand(0));
1044   if (Op == 0) return false;
1045   
1046   unsigned Opc;
1047   const Type *OpTy = I->getOperand(0)->getType();
1048   if (OpTy->isFloatTy()) Opc = ARM::VTOSIZS;
1049   else if (OpTy->isDoubleTy()) Opc = ARM::VTOSIZD;
1050   else return 0;
1051   
1052   // f64->s32 or f32->s32 both need an intermediate f32 reg.
1053   unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1054   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(Opc),
1055                           ResultReg)
1056                   .addReg(Op));
1057         
1058   // This result needs to be in an integer register, but the conversion only
1059   // takes place in fp-regs.
1060   unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1061   if (IntReg == 0) return false;
1062   
1063   UpdateValueMap(I, IntReg);
1064   return true;
1065 }
1066
1067 bool ARMFastISel::SelectSelect(const Instruction *I) {
1068   EVT VT = TLI.getValueType(I->getType(), /*HandleUnknown=*/true);
1069   if (VT == MVT::Other || !isTypeLegal(I->getType(), VT))
1070     return false;
1071
1072   // Things need to be register sized for register moves.
1073   if (VT.getSimpleVT().SimpleTy != MVT::i32) return false;
1074   const TargetRegisterClass *RC = TLI.getRegClassFor(VT);
1075
1076   unsigned CondReg = getRegForValue(I->getOperand(0));
1077   if (CondReg == 0) return false;
1078   unsigned Op1Reg = getRegForValue(I->getOperand(1));
1079   if (Op1Reg == 0) return false;
1080   unsigned Op2Reg = getRegForValue(I->getOperand(2));
1081   if (Op2Reg == 0) return false;
1082
1083   unsigned CmpOpc = isThumb ? ARM::t2TSTri : ARM::TSTri;
1084   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CmpOpc))
1085                   .addReg(CondReg).addImm(1));
1086   unsigned ResultReg = createResultReg(RC);
1087   unsigned MovCCOpc = isThumb ? ARM::t2MOVCCr : ARM::MOVCCr;
1088   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(MovCCOpc), ResultReg)
1089     .addReg(Op1Reg).addReg(Op2Reg)
1090     .addImm(ARMCC::EQ).addReg(ARM::CPSR);
1091   UpdateValueMap(I, ResultReg);
1092   return true;
1093 }
1094
1095 bool ARMFastISel::SelectSDiv(const Instruction *I) {
1096   EVT VT;
1097   const Type *Ty = I->getType();
1098   if (!isTypeLegal(Ty, VT))
1099     return false;
1100
1101   // If we have integer div support we should have selected this automagically.
1102   // In case we have a real miss go ahead and return false and we'll pick
1103   // it up later.
1104   if (Subtarget->hasDivide()) return false;  
1105   
1106   // Otherwise emit a libcall.
1107   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1108   if (VT == MVT::i16)
1109     LC = RTLIB::SDIV_I16;
1110   else if (VT == MVT::i32)
1111     LC = RTLIB::SDIV_I32;
1112   else if (VT == MVT::i64)
1113     LC = RTLIB::SDIV_I64;
1114   else if (VT == MVT::i128)
1115     LC = RTLIB::SDIV_I128;
1116   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1117     
1118   return ARMEmitLibcall(I, LC);
1119 }
1120
1121 bool ARMFastISel::SelectBinaryOp(const Instruction *I, unsigned ISDOpcode) {
1122   EVT VT  = TLI.getValueType(I->getType(), true);
1123
1124   // We can get here in the case when we want to use NEON for our fp
1125   // operations, but can't figure out how to. Just use the vfp instructions
1126   // if we have them.
1127   // FIXME: It'd be nice to use NEON instructions.
1128   const Type *Ty = I->getType();
1129   bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1130   if (isFloat && !Subtarget->hasVFP2())
1131     return false;
1132
1133   unsigned Op1 = getRegForValue(I->getOperand(0));
1134   if (Op1 == 0) return false;
1135
1136   unsigned Op2 = getRegForValue(I->getOperand(1));
1137   if (Op2 == 0) return false;
1138
1139   unsigned Opc;
1140   bool is64bit = VT.getSimpleVT().SimpleTy == MVT::f64 ||
1141                  VT.getSimpleVT().SimpleTy == MVT::i64;
1142   switch (ISDOpcode) {
1143     default: return false;
1144     case ISD::FADD:
1145       Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1146       break;
1147     case ISD::FSUB:
1148       Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1149       break;
1150     case ISD::FMUL:
1151       Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1152       break;
1153   }
1154   unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
1155   AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1156                           TII.get(Opc), ResultReg)
1157                   .addReg(Op1).addReg(Op2));
1158   UpdateValueMap(I, ResultReg);
1159   return true;
1160 }
1161
1162 // Call Handling Code
1163
1164 // This is largely taken directly from CCAssignFnForNode - we don't support
1165 // varargs in FastISel so that part has been removed.
1166 // TODO: We may not support all of this.
1167 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC, bool Return) {
1168   switch (CC) {
1169   default:
1170     llvm_unreachable("Unsupported calling convention");
1171   case CallingConv::C:
1172   case CallingConv::Fast:
1173     // Use target triple & subtarget features to do actual dispatch.
1174     if (Subtarget->isAAPCS_ABI()) {
1175       if (Subtarget->hasVFP2() &&
1176           FloatABIType == FloatABI::Hard)
1177         return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1178       else
1179         return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1180     } else
1181         return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1182   case CallingConv::ARM_AAPCS_VFP:
1183     return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1184   case CallingConv::ARM_AAPCS:
1185     return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1186   case CallingConv::ARM_APCS:
1187     return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1188   }
1189 }
1190
1191 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1192                                   SmallVectorImpl<unsigned> &ArgRegs,
1193                                   SmallVectorImpl<EVT> &ArgVTs,
1194                                   SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1195                                   SmallVectorImpl<unsigned> &RegArgs,
1196                                   CallingConv::ID CC,
1197                                   unsigned &NumBytes) {
1198   SmallVector<CCValAssign, 16> ArgLocs;
1199   CCState CCInfo(CC, false, TM, ArgLocs, *Context);
1200   CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags, CCAssignFnForCall(CC, false));
1201
1202   // Get a count of how many bytes are to be pushed on the stack.
1203   NumBytes = CCInfo.getNextStackOffset();
1204
1205   // Issue CALLSEQ_START
1206   unsigned AdjStackDown = TM.getRegisterInfo()->getCallFrameSetupOpcode();
1207   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackDown))
1208           .addImm(NumBytes);
1209
1210   // Process the args.
1211   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1212     CCValAssign &VA = ArgLocs[i];
1213     unsigned Arg = ArgRegs[VA.getValNo()];
1214     EVT ArgVT = ArgVTs[VA.getValNo()];
1215
1216     // Handle arg promotion, etc.
1217     switch (VA.getLocInfo()) {
1218       case CCValAssign::Full: break;
1219       default:
1220       // TODO: Handle arg promotion.
1221       return false;
1222     }
1223
1224     // Now copy/store arg to correct locations.
1225     if (VA.isRegLoc()) {
1226       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1227               VA.getLocReg())
1228       .addReg(Arg);
1229       RegArgs.push_back(VA.getLocReg());
1230     } else {
1231       // Need to store
1232       return false;
1233     }
1234   }
1235   
1236   return true;
1237 }
1238
1239 bool ARMFastISel::FinishCall(EVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
1240                              const Instruction *I, CallingConv::ID CC,
1241                              unsigned &NumBytes) {
1242   // Issue CALLSEQ_END
1243   unsigned AdjStackUp = TM.getRegisterInfo()->getCallFrameDestroyOpcode();
1244   BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(AdjStackUp))
1245           .addImm(NumBytes).addImm(0);
1246
1247   // Now the return value.
1248   if (RetVT.getSimpleVT().SimpleTy != MVT::isVoid) {
1249     SmallVector<CCValAssign, 16> RVLocs;
1250     CCState CCInfo(CC, false, TM, RVLocs, *Context);
1251     CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true));
1252
1253     // Copy all of the result registers out of their specified physreg.
1254     if (RVLocs.size() == 2 && RetVT.getSimpleVT().SimpleTy == MVT::f64) {
1255       // For this move we copy into two registers and then move into the
1256       // double fp reg we want.
1257       // TODO: Are the copies necessary?
1258       TargetRegisterClass *CopyRC = TLI.getRegClassFor(MVT::i32);
1259       unsigned Copy1 = createResultReg(CopyRC);
1260       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1261               Copy1).addReg(RVLocs[0].getLocReg());
1262       UsedRegs.push_back(RVLocs[0].getLocReg());
1263       
1264       unsigned Copy2 = createResultReg(CopyRC);
1265       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1266               Copy2).addReg(RVLocs[1].getLocReg());
1267       UsedRegs.push_back(RVLocs[1].getLocReg());
1268       
1269       EVT DestVT = RVLocs[0].getValVT();
1270       TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
1271       unsigned ResultReg = createResultReg(DstRC);
1272       AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL,
1273                               TII.get(ARM::VMOVDRR), ResultReg)
1274                       .addReg(Copy1).addReg(Copy2));
1275                               
1276       // Finally update the result.        
1277       UpdateValueMap(I, ResultReg);
1278     } else {
1279       assert(RVLocs.size() == 1 && "Can't handle non-double multi-reg retvals!");
1280       EVT CopyVT = RVLocs[0].getValVT();
1281       TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
1282
1283       unsigned ResultReg = createResultReg(DstRC);
1284       BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(TargetOpcode::COPY),
1285               ResultReg).addReg(RVLocs[0].getLocReg());
1286       UsedRegs.push_back(RVLocs[0].getLocReg());
1287
1288       // Finally update the result.        
1289       UpdateValueMap(I, ResultReg);
1290     }
1291   }
1292
1293   return true;                           
1294 }
1295
1296 // A quick function that will emit a call for a named libcall in F with the
1297 // vector of passed arguments for the Instruction in I. We can assume that we
1298 // can emit a call for any libcall we can produce. This is an abridged version 
1299 // of the full call infrastructure since we won't need to worry about things 
1300 // like computed function pointers or strange arguments at call sites.
1301 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
1302 // with X86.
1303 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
1304   CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
1305     
1306   // Handle *simple* calls for now.
1307   const Type *RetTy = I->getType();
1308   EVT RetVT;
1309   if (RetTy->isVoidTy())
1310     RetVT = MVT::isVoid;
1311   else if (!isTypeLegal(RetTy, RetVT))
1312     return false;
1313   
1314   // For now we're using BLX etc on the assumption that we have v5t ops.
1315   if (!Subtarget->hasV5TOps()) return false;
1316   
1317   // Set up the argument vectors.
1318   SmallVector<Value*, 8> Args;
1319   SmallVector<unsigned, 8> ArgRegs;
1320   SmallVector<EVT, 8> ArgVTs;
1321   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1322   Args.reserve(I->getNumOperands());
1323   ArgRegs.reserve(I->getNumOperands());
1324   ArgVTs.reserve(I->getNumOperands());
1325   ArgFlags.reserve(I->getNumOperands());
1326   for (unsigned i = 0; i < I->getNumOperands(); ++i) {
1327     Value *Op = I->getOperand(i);
1328     unsigned Arg = getRegForValue(Op);
1329     if (Arg == 0) return false;
1330     
1331     const Type *ArgTy = Op->getType();
1332     EVT ArgVT;
1333     if (!isTypeLegal(ArgTy, ArgVT)) return false;
1334     
1335     ISD::ArgFlagsTy Flags;
1336     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1337     Flags.setOrigAlign(OriginalAlignment);
1338     
1339     Args.push_back(Op);
1340     ArgRegs.push_back(Arg);
1341     ArgVTs.push_back(ArgVT);
1342     ArgFlags.push_back(Flags);
1343   }
1344   
1345   // Handle the arguments now that we've gotten them.
1346   SmallVector<unsigned, 4> RegArgs;
1347   unsigned NumBytes;
1348   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1349     return false;
1350   
1351   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1352   // TODO: Turn this into the table of arm call ops.  
1353   MachineInstrBuilder MIB;
1354   unsigned CallOpc;
1355   if(isThumb)
1356     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1357   else
1358     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1359   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1360         .addExternalSymbol(TLI.getLibcallName(Call));
1361     
1362   // Add implicit physical register uses to the call.
1363   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1364     MIB.addReg(RegArgs[i]);
1365     
1366   // Finish off the call including any return values.
1367   SmallVector<unsigned, 4> UsedRegs;  
1368   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1369   
1370   // Set all unused physreg defs as dead.
1371   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1372   
1373   return true;
1374 }
1375
1376 bool ARMFastISel::SelectCall(const Instruction *I) {
1377   const CallInst *CI = cast<CallInst>(I);
1378   const Value *Callee = CI->getCalledValue();
1379
1380   // Can't handle inline asm or worry about intrinsics yet.
1381   if (isa<InlineAsm>(Callee) || isa<IntrinsicInst>(CI)) return false;
1382
1383   // Only handle global variable Callees that are direct calls.
1384   const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
1385   if (!GV || Subtarget->GVIsIndirectSymbol(GV, TM.getRelocationModel()))
1386     return false;
1387   
1388   // Check the calling convention.
1389   ImmutableCallSite CS(CI);
1390   CallingConv::ID CC = CS.getCallingConv();
1391   // TODO: Avoid some calling conventions?
1392   if (CC != CallingConv::C) {
1393     // errs() << "Can't handle calling convention: " << CC << "\n";
1394     return false;
1395   }
1396   
1397   // Let SDISel handle vararg functions.
1398   const PointerType *PT = cast<PointerType>(CS.getCalledValue()->getType());
1399   const FunctionType *FTy = cast<FunctionType>(PT->getElementType());
1400   if (FTy->isVarArg())
1401     return false;
1402   
1403   // Handle *simple* calls for now.
1404   const Type *RetTy = I->getType();
1405   EVT RetVT;
1406   if (RetTy->isVoidTy())
1407     RetVT = MVT::isVoid;
1408   else if (!isTypeLegal(RetTy, RetVT))
1409     return false;
1410   
1411   // For now we're using BLX etc on the assumption that we have v5t ops.
1412   // TODO: Maybe?
1413   if (!Subtarget->hasV5TOps()) return false;
1414   
1415   // Set up the argument vectors.
1416   SmallVector<Value*, 8> Args;
1417   SmallVector<unsigned, 8> ArgRegs;
1418   SmallVector<EVT, 8> ArgVTs;
1419   SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
1420   Args.reserve(CS.arg_size());
1421   ArgRegs.reserve(CS.arg_size());
1422   ArgVTs.reserve(CS.arg_size());
1423   ArgFlags.reserve(CS.arg_size());
1424   for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
1425        i != e; ++i) {
1426     unsigned Arg = getRegForValue(*i);
1427     
1428     if (Arg == 0)
1429       return false;
1430     ISD::ArgFlagsTy Flags;
1431     unsigned AttrInd = i - CS.arg_begin() + 1;
1432     if (CS.paramHasAttr(AttrInd, Attribute::SExt))
1433       Flags.setSExt();
1434     if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
1435       Flags.setZExt();
1436
1437          // FIXME: Only handle *easy* calls for now.
1438     if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
1439         CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
1440         CS.paramHasAttr(AttrInd, Attribute::Nest) ||
1441         CS.paramHasAttr(AttrInd, Attribute::ByVal))
1442       return false;
1443
1444     const Type *ArgTy = (*i)->getType();
1445     EVT ArgVT;
1446     if (!isTypeLegal(ArgTy, ArgVT))
1447       return false;
1448     unsigned OriginalAlignment = TD.getABITypeAlignment(ArgTy);
1449     Flags.setOrigAlign(OriginalAlignment);
1450     
1451     Args.push_back(*i);
1452     ArgRegs.push_back(Arg);
1453     ArgVTs.push_back(ArgVT);
1454     ArgFlags.push_back(Flags);
1455   }
1456   
1457   // Handle the arguments now that we've gotten them.
1458   SmallVector<unsigned, 4> RegArgs;
1459   unsigned NumBytes;
1460   if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags, RegArgs, CC, NumBytes))
1461     return false;
1462   
1463   // Issue the call, BLXr9 for darwin, BLX otherwise. This uses V5 ops.
1464   // TODO: Turn this into the table of arm call ops.  
1465   MachineInstrBuilder MIB;
1466   unsigned CallOpc;
1467   if(isThumb)
1468     CallOpc = Subtarget->isTargetDarwin() ? ARM::tBLXi_r9 : ARM::tBLXi;
1469   else
1470     CallOpc = Subtarget->isTargetDarwin() ? ARM::BLr9 : ARM::BL;
1471   MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DL, TII.get(CallOpc))
1472               .addGlobalAddress(GV, 0, 0);
1473     
1474   // Add implicit physical register uses to the call.
1475   for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
1476     MIB.addReg(RegArgs[i]);
1477     
1478   // Finish off the call including any return values.
1479   SmallVector<unsigned, 4> UsedRegs;  
1480   if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes)) return false;
1481   
1482   // Set all unused physreg defs as dead.
1483   static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
1484   
1485   return true;
1486   
1487 }
1488
1489 // TODO: SoftFP support.
1490 bool ARMFastISel::TargetSelectInstruction(const Instruction *I) {
1491   // No Thumb-1 for now.
1492   if (isThumb && !AFI->isThumb2Function()) return false;
1493
1494   switch (I->getOpcode()) {
1495     case Instruction::Load:
1496       return SelectLoad(I);
1497     case Instruction::Store:
1498       return SelectStore(I);
1499     case Instruction::Br:
1500       return SelectBranch(I);
1501     case Instruction::ICmp:
1502     case Instruction::FCmp:
1503       return SelectCmp(I);
1504     case Instruction::FPExt:
1505       return SelectFPExt(I);
1506     case Instruction::FPTrunc:
1507       return SelectFPTrunc(I);
1508     case Instruction::SIToFP:
1509       return SelectSIToFP(I);
1510     case Instruction::FPToSI:
1511       return SelectFPToSI(I);
1512     case Instruction::FAdd:
1513       return SelectBinaryOp(I, ISD::FADD);
1514     case Instruction::FSub:
1515       return SelectBinaryOp(I, ISD::FSUB);
1516     case Instruction::FMul:
1517       return SelectBinaryOp(I, ISD::FMUL);
1518     case Instruction::SDiv:
1519       return SelectSDiv(I);
1520     case Instruction::Call:
1521       return SelectCall(I);
1522     case Instruction::Select:
1523       return SelectSelect(I);
1524     default: break;
1525   }
1526   return false;
1527 }
1528
1529 namespace llvm {
1530   llvm::FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo) {
1531     if (EnableARMFastISel) return new ARMFastISel(funcInfo);
1532     return 0;
1533   }
1534 }