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