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