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