1 //===-- ARMFastISel.cpp - ARM FastISel implementation ---------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ARM-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // ARMGenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "ARMBaseRegisterInfo.h"
18 #include "ARMCallingConv.h"
19 #include "ARMConstantPoolValue.h"
20 #include "ARMISelLowering.h"
21 #include "ARMMachineFunctionInfo.h"
22 #include "ARMSubtarget.h"
23 #include "MCTargetDesc/ARMAddressingModes.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/CodeGen/FastISel.h"
26 #include "llvm/CodeGen/FunctionLoweringInfo.h"
27 #include "llvm/CodeGen/MachineConstantPool.h"
28 #include "llvm/CodeGen/MachineFrameInfo.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/CodeGen/MachineMemOperand.h"
31 #include "llvm/CodeGen/MachineModuleInfo.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/IR/CallSite.h"
34 #include "llvm/IR/CallingConv.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/DerivedTypes.h"
37 #include "llvm/IR/GetElementPtrTypeIterator.h"
38 #include "llvm/IR/GlobalVariable.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Module.h"
42 #include "llvm/IR/Operator.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Target/TargetInstrInfo.h"
45 #include "llvm/Target/TargetLowering.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Target/TargetOptions.h"
52 // All possible address modes, plus some.
53 typedef struct Address {
66 // Innocuous defaults for our address.
68 : BaseType(RegBase), Offset(0) {
73 class ARMFastISel final : public FastISel {
75 /// Subtarget - Keep a pointer to the ARMSubtarget around so that we can
76 /// make the right decision when generating code for different targets.
77 const ARMSubtarget *Subtarget;
79 const TargetMachine &TM;
80 const TargetInstrInfo &TII;
81 const TargetLowering &TLI;
84 // Convenience variables to avoid some queries.
89 explicit ARMFastISel(FunctionLoweringInfo &funcInfo,
90 const TargetLibraryInfo *libInfo)
91 : FastISel(funcInfo, libInfo),
93 &static_cast<const ARMSubtarget &>(funcInfo.MF->getSubtarget())),
94 M(const_cast<Module &>(*funcInfo.Fn->getParent())),
95 TM(funcInfo.MF->getTarget()), TII(*Subtarget->getInstrInfo()),
96 TLI(*Subtarget->getTargetLowering()) {
97 AFI = funcInfo.MF->getInfo<ARMFunctionInfo>();
98 isThumb2 = AFI->isThumbFunction();
99 Context = &funcInfo.Fn->getContext();
102 // Code from FastISel.cpp.
104 unsigned fastEmitInst_r(unsigned MachineInstOpcode,
105 const TargetRegisterClass *RC,
106 unsigned Op0, bool Op0IsKill);
107 unsigned fastEmitInst_rr(unsigned MachineInstOpcode,
108 const TargetRegisterClass *RC,
109 unsigned Op0, bool Op0IsKill,
110 unsigned Op1, bool Op1IsKill);
111 unsigned fastEmitInst_ri(unsigned MachineInstOpcode,
112 const TargetRegisterClass *RC,
113 unsigned Op0, bool Op0IsKill,
115 unsigned fastEmitInst_rri(unsigned MachineInstOpcode,
116 const TargetRegisterClass *RC,
117 unsigned Op0, bool Op0IsKill,
118 unsigned Op1, bool Op1IsKill,
120 unsigned fastEmitInst_i(unsigned MachineInstOpcode,
121 const TargetRegisterClass *RC,
124 // Backend specific FastISel code.
126 bool fastSelectInstruction(const Instruction *I) override;
127 unsigned fastMaterializeConstant(const Constant *C) override;
128 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
129 bool tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
130 const LoadInst *LI) override;
131 bool fastLowerArguments() override;
133 #include "ARMGenFastISel.inc"
135 // Instruction selection routines.
137 bool SelectLoad(const Instruction *I);
138 bool SelectStore(const Instruction *I);
139 bool SelectBranch(const Instruction *I);
140 bool SelectIndirectBr(const Instruction *I);
141 bool SelectCmp(const Instruction *I);
142 bool SelectFPExt(const Instruction *I);
143 bool SelectFPTrunc(const Instruction *I);
144 bool SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode);
145 bool SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode);
146 bool SelectIToFP(const Instruction *I, bool isSigned);
147 bool SelectFPToI(const Instruction *I, bool isSigned);
148 bool SelectDiv(const Instruction *I, bool isSigned);
149 bool SelectRem(const Instruction *I, bool isSigned);
150 bool SelectCall(const Instruction *I, const char *IntrMemName);
151 bool SelectIntrinsicCall(const IntrinsicInst &I);
152 bool SelectSelect(const Instruction *I);
153 bool SelectRet(const Instruction *I);
154 bool SelectTrunc(const Instruction *I);
155 bool SelectIntExt(const Instruction *I);
156 bool SelectShift(const Instruction *I, ARM_AM::ShiftOpc ShiftTy);
160 bool isPositionIndependent() const;
161 bool isTypeLegal(Type *Ty, MVT &VT);
162 bool isLoadTypeLegal(Type *Ty, MVT &VT);
163 bool ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
165 bool ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
166 unsigned Alignment = 0, bool isZExt = true,
167 bool allocReg = true);
168 bool ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
169 unsigned Alignment = 0);
170 bool ARMComputeAddress(const Value *Obj, Address &Addr);
171 void ARMSimplifyAddress(Address &Addr, MVT VT, bool useAM3);
172 bool ARMIsMemCpySmall(uint64_t Len);
173 bool ARMTryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
175 unsigned ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
176 unsigned ARMMaterializeFP(const ConstantFP *CFP, MVT VT);
177 unsigned ARMMaterializeInt(const Constant *C, MVT VT);
178 unsigned ARMMaterializeGV(const GlobalValue *GV, MVT VT);
179 unsigned ARMMoveToFPReg(MVT VT, unsigned SrcReg);
180 unsigned ARMMoveToIntReg(MVT VT, unsigned SrcReg);
181 unsigned ARMSelectCallOp(bool UseReg);
182 unsigned ARMLowerPICELF(const GlobalValue *GV, unsigned Align, MVT VT);
184 const TargetLowering *getTargetLowering() { return &TLI; }
186 // Call handling routines.
188 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC,
191 bool ProcessCallArgs(SmallVectorImpl<Value*> &Args,
192 SmallVectorImpl<unsigned> &ArgRegs,
193 SmallVectorImpl<MVT> &ArgVTs,
194 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
195 SmallVectorImpl<unsigned> &RegArgs,
199 unsigned getLibcallReg(const Twine &Name);
200 bool FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
201 const Instruction *I, CallingConv::ID CC,
202 unsigned &NumBytes, bool isVarArg);
203 bool ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call);
205 // OptionalDef handling routines.
207 bool isARMNEONPred(const MachineInstr *MI);
208 bool DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR);
209 const MachineInstrBuilder &AddOptionalDefs(const MachineInstrBuilder &MIB);
210 void AddLoadStoreOperands(MVT VT, Address &Addr,
211 const MachineInstrBuilder &MIB,
212 MachineMemOperand::Flags Flags, bool useAM3);
215 } // end anonymous namespace
217 #include "ARMGenCallingConv.inc"
219 // DefinesOptionalPredicate - This is different from DefinesPredicate in that
220 // we don't care about implicit defs here, just places we'll need to add a
221 // default CCReg argument. Sets CPSR if we're setting CPSR instead of CCR.
222 bool ARMFastISel::DefinesOptionalPredicate(MachineInstr *MI, bool *CPSR) {
223 if (!MI->hasOptionalDef())
226 // Look to see if our OptionalDef is defining CPSR or CCR.
227 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
228 const MachineOperand &MO = MI->getOperand(i);
229 if (!MO.isReg() || !MO.isDef()) continue;
230 if (MO.getReg() == ARM::CPSR)
236 bool ARMFastISel::isARMNEONPred(const MachineInstr *MI) {
237 const MCInstrDesc &MCID = MI->getDesc();
239 // If we're a thumb2 or not NEON function we'll be handled via isPredicable.
240 if ((MCID.TSFlags & ARMII::DomainMask) != ARMII::DomainNEON ||
241 AFI->isThumb2Function())
242 return MI->isPredicable();
244 for (unsigned i = 0, e = MCID.getNumOperands(); i != e; ++i)
245 if (MCID.OpInfo[i].isPredicate())
251 // If the machine is predicable go ahead and add the predicate operands, if
252 // it needs default CC operands add those.
253 // TODO: If we want to support thumb1 then we'll need to deal with optional
254 // CPSR defs that need to be added before the remaining operands. See s_cc_out
255 // for descriptions why.
256 const MachineInstrBuilder &
257 ARMFastISel::AddOptionalDefs(const MachineInstrBuilder &MIB) {
258 MachineInstr *MI = &*MIB;
260 // Do we use a predicate? or...
261 // Are we NEON in ARM mode and have a predicate operand? If so, I know
262 // we're not predicable but add it anyways.
263 if (isARMNEONPred(MI))
266 // Do we optionally set a predicate? Preds is size > 0 iff the predicate
267 // defines CPSR. All other OptionalDefines in ARM are the CCR register.
269 if (DefinesOptionalPredicate(MI, &CPSR)) {
278 unsigned ARMFastISel::fastEmitInst_r(unsigned MachineInstOpcode,
279 const TargetRegisterClass *RC,
280 unsigned Op0, bool Op0IsKill) {
281 unsigned ResultReg = createResultReg(RC);
282 const MCInstrDesc &II = TII.get(MachineInstOpcode);
284 // Make sure the input operand is sufficiently constrained to be legal
285 // for this instruction.
286 Op0 = constrainOperandRegClass(II, Op0, 1);
287 if (II.getNumDefs() >= 1) {
288 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
289 ResultReg).addReg(Op0, Op0IsKill * RegState::Kill));
291 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
292 .addReg(Op0, Op0IsKill * RegState::Kill));
293 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
294 TII.get(TargetOpcode::COPY), ResultReg)
295 .addReg(II.ImplicitDefs[0]));
300 unsigned ARMFastISel::fastEmitInst_rr(unsigned MachineInstOpcode,
301 const TargetRegisterClass *RC,
302 unsigned Op0, bool Op0IsKill,
303 unsigned Op1, bool Op1IsKill) {
304 unsigned ResultReg = createResultReg(RC);
305 const MCInstrDesc &II = TII.get(MachineInstOpcode);
307 // Make sure the input operands are sufficiently constrained to be legal
308 // for this instruction.
309 Op0 = constrainOperandRegClass(II, Op0, 1);
310 Op1 = constrainOperandRegClass(II, Op1, 2);
312 if (II.getNumDefs() >= 1) {
314 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
315 .addReg(Op0, Op0IsKill * RegState::Kill)
316 .addReg(Op1, Op1IsKill * RegState::Kill));
318 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
319 .addReg(Op0, Op0IsKill * RegState::Kill)
320 .addReg(Op1, Op1IsKill * RegState::Kill));
321 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
322 TII.get(TargetOpcode::COPY), ResultReg)
323 .addReg(II.ImplicitDefs[0]));
328 unsigned ARMFastISel::fastEmitInst_ri(unsigned MachineInstOpcode,
329 const TargetRegisterClass *RC,
330 unsigned Op0, bool Op0IsKill,
332 unsigned ResultReg = createResultReg(RC);
333 const MCInstrDesc &II = TII.get(MachineInstOpcode);
335 // Make sure the input operand is sufficiently constrained to be legal
336 // for this instruction.
337 Op0 = constrainOperandRegClass(II, Op0, 1);
338 if (II.getNumDefs() >= 1) {
340 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
341 .addReg(Op0, Op0IsKill * RegState::Kill)
344 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
345 .addReg(Op0, Op0IsKill * RegState::Kill)
347 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
348 TII.get(TargetOpcode::COPY), ResultReg)
349 .addReg(II.ImplicitDefs[0]));
354 unsigned ARMFastISel::fastEmitInst_rri(unsigned MachineInstOpcode,
355 const TargetRegisterClass *RC,
356 unsigned Op0, bool Op0IsKill,
357 unsigned Op1, bool Op1IsKill,
359 unsigned ResultReg = createResultReg(RC);
360 const MCInstrDesc &II = TII.get(MachineInstOpcode);
362 // Make sure the input operands are sufficiently constrained to be legal
363 // for this instruction.
364 Op0 = constrainOperandRegClass(II, Op0, 1);
365 Op1 = constrainOperandRegClass(II, Op1, 2);
366 if (II.getNumDefs() >= 1) {
368 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
369 .addReg(Op0, Op0IsKill * RegState::Kill)
370 .addReg(Op1, Op1IsKill * RegState::Kill)
373 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
374 .addReg(Op0, Op0IsKill * RegState::Kill)
375 .addReg(Op1, Op1IsKill * RegState::Kill)
377 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
378 TII.get(TargetOpcode::COPY), ResultReg)
379 .addReg(II.ImplicitDefs[0]));
384 unsigned ARMFastISel::fastEmitInst_i(unsigned MachineInstOpcode,
385 const TargetRegisterClass *RC,
387 unsigned ResultReg = createResultReg(RC);
388 const MCInstrDesc &II = TII.get(MachineInstOpcode);
390 if (II.getNumDefs() >= 1) {
391 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II,
392 ResultReg).addImm(Imm));
394 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
396 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
397 TII.get(TargetOpcode::COPY), ResultReg)
398 .addReg(II.ImplicitDefs[0]));
403 // TODO: Don't worry about 64-bit now, but when this is fixed remove the
404 // checks from the various callers.
405 unsigned ARMFastISel::ARMMoveToFPReg(MVT VT, unsigned SrcReg) {
406 if (VT == MVT::f64) return 0;
408 unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
409 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
410 TII.get(ARM::VMOVSR), MoveReg)
415 unsigned ARMFastISel::ARMMoveToIntReg(MVT VT, unsigned SrcReg) {
416 if (VT == MVT::i64) return 0;
418 unsigned MoveReg = createResultReg(TLI.getRegClassFor(VT));
419 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
420 TII.get(ARM::VMOVRS), MoveReg)
425 // For double width floating point we need to materialize two constants
426 // (the high and the low) into integer registers then use a move to get
427 // the combined constant into an FP reg.
428 unsigned ARMFastISel::ARMMaterializeFP(const ConstantFP *CFP, MVT VT) {
429 const APFloat Val = CFP->getValueAPF();
430 bool is64bit = VT == MVT::f64;
432 // This checks to see if we can use VFP3 instructions to materialize
433 // a constant, otherwise we have to go through the constant pool.
434 if (TLI.isFPImmLegal(Val, VT)) {
438 Imm = ARM_AM::getFP64Imm(Val);
441 Imm = ARM_AM::getFP32Imm(Val);
444 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
445 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
446 TII.get(Opc), DestReg).addImm(Imm));
450 // Require VFP2 for loading fp constants.
451 if (!Subtarget->hasVFP2()) return false;
453 // MachineConstantPool wants an explicit alignment.
454 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
456 // TODO: Figure out if this is correct.
457 Align = DL.getTypeAllocSize(CFP->getType());
459 unsigned Idx = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
460 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
461 unsigned Opc = is64bit ? ARM::VLDRD : ARM::VLDRS;
463 // The extra reg is for addrmode5.
465 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
466 .addConstantPoolIndex(Idx)
471 unsigned ARMFastISel::ARMMaterializeInt(const Constant *C, MVT VT) {
473 if (VT != MVT::i32 && VT != MVT::i16 && VT != MVT::i8 && VT != MVT::i1)
476 // If we can do this in a single instruction without a constant pool entry
478 const ConstantInt *CI = cast<ConstantInt>(C);
479 if (Subtarget->hasV6T2Ops() && isUInt<16>(CI->getZExtValue())) {
480 unsigned Opc = isThumb2 ? ARM::t2MOVi16 : ARM::MOVi16;
481 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass :
483 unsigned ImmReg = createResultReg(RC);
484 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
485 TII.get(Opc), ImmReg)
486 .addImm(CI->getZExtValue()));
490 // Use MVN to emit negative constants.
491 if (VT == MVT::i32 && Subtarget->hasV6T2Ops() && CI->isNegative()) {
492 unsigned Imm = (unsigned)~(CI->getSExtValue());
493 bool UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
494 (ARM_AM::getSOImmVal(Imm) != -1);
496 unsigned Opc = isThumb2 ? ARM::t2MVNi : ARM::MVNi;
497 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass :
499 unsigned ImmReg = createResultReg(RC);
500 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
501 TII.get(Opc), ImmReg)
507 unsigned ResultReg = 0;
508 if (Subtarget->useMovt(*FuncInfo.MF))
509 ResultReg = fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
514 // Load from constant pool. For now 32-bit only.
518 // MachineConstantPool wants an explicit alignment.
519 unsigned Align = DL.getPrefTypeAlignment(C->getType());
521 // TODO: Figure out if this is correct.
522 Align = DL.getTypeAllocSize(C->getType());
524 unsigned Idx = MCP.getConstantPoolIndex(C, Align);
525 ResultReg = createResultReg(TLI.getRegClassFor(VT));
527 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
528 TII.get(ARM::t2LDRpci), ResultReg)
529 .addConstantPoolIndex(Idx));
531 // The extra immediate is for addrmode2.
532 ResultReg = constrainOperandRegClass(TII.get(ARM::LDRcp), ResultReg, 0);
533 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
534 TII.get(ARM::LDRcp), ResultReg)
535 .addConstantPoolIndex(Idx)
541 bool ARMFastISel::isPositionIndependent() const {
542 return TLI.isPositionIndependent();
545 unsigned ARMFastISel::ARMMaterializeGV(const GlobalValue *GV, MVT VT) {
546 // For now 32-bit only.
547 if (VT != MVT::i32 || GV->isThreadLocal()) return 0;
549 bool IsIndirect = Subtarget->isGVIndirectSymbol(GV);
550 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass
552 unsigned DestReg = createResultReg(RC);
554 // FastISel TLS support on non-MachO is broken, punt to SelectionDAG.
555 const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
556 bool IsThreadLocal = GVar && GVar->isThreadLocal();
557 if (!Subtarget->isTargetMachO() && IsThreadLocal) return 0;
559 bool IsPositionIndependent = isPositionIndependent();
560 // Use movw+movt when possible, it avoids constant pool entries.
561 // Non-darwin targets only support static movt relocations in FastISel.
562 if (Subtarget->useMovt(*FuncInfo.MF) &&
563 (Subtarget->isTargetMachO() || !IsPositionIndependent)) {
565 unsigned char TF = 0;
566 if (Subtarget->isTargetMachO())
567 TF = ARMII::MO_NONLAZY;
569 if (IsPositionIndependent)
570 Opc = isThumb2 ? ARM::t2MOV_ga_pcrel : ARM::MOV_ga_pcrel;
572 Opc = isThumb2 ? ARM::t2MOVi32imm : ARM::MOVi32imm;
573 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
574 TII.get(Opc), DestReg).addGlobalAddress(GV, 0, TF));
576 // MachineConstantPool wants an explicit alignment.
577 unsigned Align = DL.getPrefTypeAlignment(GV->getType());
579 // TODO: Figure out if this is correct.
580 Align = DL.getTypeAllocSize(GV->getType());
583 if (Subtarget->isTargetELF() && IsPositionIndependent)
584 return ARMLowerPICELF(GV, Align, VT);
587 unsigned PCAdj = IsPositionIndependent ? (Subtarget->isThumb() ? 4 : 8) : 0;
588 unsigned Id = AFI->createPICLabelUId();
589 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(GV, Id,
592 unsigned Idx = MCP.getConstantPoolIndex(CPV, Align);
595 MachineInstrBuilder MIB;
597 unsigned Opc = IsPositionIndependent ? ARM::t2LDRpci_pic : ARM::t2LDRpci;
598 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc),
599 DestReg).addConstantPoolIndex(Idx);
600 if (IsPositionIndependent)
602 AddOptionalDefs(MIB);
604 // The extra immediate is for addrmode2.
605 DestReg = constrainOperandRegClass(TII.get(ARM::LDRcp), DestReg, 0);
606 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
607 TII.get(ARM::LDRcp), DestReg)
608 .addConstantPoolIndex(Idx)
610 AddOptionalDefs(MIB);
612 if (IsPositionIndependent) {
613 unsigned Opc = IsIndirect ? ARM::PICLDR : ARM::PICADD;
614 unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
616 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
617 DbgLoc, TII.get(Opc), NewDestReg)
620 AddOptionalDefs(MIB);
627 MachineInstrBuilder MIB;
628 unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
630 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
631 TII.get(ARM::t2LDRi12), NewDestReg)
635 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
636 TII.get(ARM::LDRi12), NewDestReg)
639 DestReg = NewDestReg;
640 AddOptionalDefs(MIB);
646 unsigned ARMFastISel::fastMaterializeConstant(const Constant *C) {
647 EVT CEVT = TLI.getValueType(DL, C->getType(), true);
649 // Only handle simple types.
650 if (!CEVT.isSimple()) return 0;
651 MVT VT = CEVT.getSimpleVT();
653 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
654 return ARMMaterializeFP(CFP, VT);
655 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
656 return ARMMaterializeGV(GV, VT);
657 else if (isa<ConstantInt>(C))
658 return ARMMaterializeInt(C, VT);
663 // TODO: unsigned ARMFastISel::TargetMaterializeFloatZero(const ConstantFP *CF);
665 unsigned ARMFastISel::fastMaterializeAlloca(const AllocaInst *AI) {
666 // Don't handle dynamic allocas.
667 if (!FuncInfo.StaticAllocaMap.count(AI)) return 0;
670 if (!isLoadTypeLegal(AI->getType(), VT)) return 0;
672 DenseMap<const AllocaInst*, int>::iterator SI =
673 FuncInfo.StaticAllocaMap.find(AI);
675 // This will get lowered later into the correct offsets and registers
676 // via rewriteXFrameIndex.
677 if (SI != FuncInfo.StaticAllocaMap.end()) {
678 unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
679 const TargetRegisterClass* RC = TLI.getRegClassFor(VT);
680 unsigned ResultReg = createResultReg(RC);
681 ResultReg = constrainOperandRegClass(TII.get(Opc), ResultReg, 0);
683 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
684 TII.get(Opc), ResultReg)
685 .addFrameIndex(SI->second)
693 bool ARMFastISel::isTypeLegal(Type *Ty, MVT &VT) {
694 EVT evt = TLI.getValueType(DL, Ty, true);
696 // Only handle simple types.
697 if (evt == MVT::Other || !evt.isSimple()) return false;
698 VT = evt.getSimpleVT();
700 // Handle all legal types, i.e. a register that will directly hold this
702 return TLI.isTypeLegal(VT);
705 bool ARMFastISel::isLoadTypeLegal(Type *Ty, MVT &VT) {
706 if (isTypeLegal(Ty, VT)) return true;
708 // If this is a type than can be sign or zero-extended to a basic operation
709 // go ahead and accept it now.
710 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
716 // Computes the address to get to an object.
717 bool ARMFastISel::ARMComputeAddress(const Value *Obj, Address &Addr) {
718 // Some boilerplate from the X86 FastISel.
719 const User *U = nullptr;
720 unsigned Opcode = Instruction::UserOp1;
721 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
722 // Don't walk into other basic blocks unless the object is an alloca from
723 // another block, otherwise it may not have a virtual register assigned.
724 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
725 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
726 Opcode = I->getOpcode();
729 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
730 Opcode = C->getOpcode();
734 if (PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
735 if (Ty->getAddressSpace() > 255)
736 // Fast instruction selection doesn't support the special
743 case Instruction::BitCast:
744 // Look through bitcasts.
745 return ARMComputeAddress(U->getOperand(0), Addr);
746 case Instruction::IntToPtr:
747 // Look past no-op inttoptrs.
748 if (TLI.getValueType(DL, U->getOperand(0)->getType()) ==
749 TLI.getPointerTy(DL))
750 return ARMComputeAddress(U->getOperand(0), Addr);
752 case Instruction::PtrToInt:
753 // Look past no-op ptrtoints.
754 if (TLI.getValueType(DL, U->getType()) == TLI.getPointerTy(DL))
755 return ARMComputeAddress(U->getOperand(0), Addr);
757 case Instruction::GetElementPtr: {
758 Address SavedAddr = Addr;
759 int TmpOffset = Addr.Offset;
761 // Iterate through the GEP folding the constants into offsets where
763 gep_type_iterator GTI = gep_type_begin(U);
764 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end();
765 i != e; ++i, ++GTI) {
766 const Value *Op = *i;
767 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
768 const StructLayout *SL = DL.getStructLayout(STy);
769 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
770 TmpOffset += SL->getElementOffset(Idx);
772 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
774 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
775 // Constant-offset addressing.
776 TmpOffset += CI->getSExtValue() * S;
779 if (canFoldAddIntoGEP(U, Op)) {
780 // A compatible add with a constant operand. Fold the constant.
782 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
783 TmpOffset += CI->getSExtValue() * S;
784 // Iterate on the other operand.
785 Op = cast<AddOperator>(Op)->getOperand(0);
789 goto unsupported_gep;
794 // Try to grab the base operand now.
795 Addr.Offset = TmpOffset;
796 if (ARMComputeAddress(U->getOperand(0), Addr)) return true;
798 // We failed, restore everything and try the other options.
804 case Instruction::Alloca: {
805 const AllocaInst *AI = cast<AllocaInst>(Obj);
806 DenseMap<const AllocaInst*, int>::iterator SI =
807 FuncInfo.StaticAllocaMap.find(AI);
808 if (SI != FuncInfo.StaticAllocaMap.end()) {
809 Addr.BaseType = Address::FrameIndexBase;
810 Addr.Base.FI = SI->second;
817 // Try to get this in a register if nothing else has worked.
818 if (Addr.Base.Reg == 0) Addr.Base.Reg = getRegForValue(Obj);
819 return Addr.Base.Reg != 0;
822 void ARMFastISel::ARMSimplifyAddress(Address &Addr, MVT VT, bool useAM3) {
823 bool needsLowering = false;
824 switch (VT.SimpleTy) {
825 default: llvm_unreachable("Unhandled load/store type!");
831 // Integer loads/stores handle 12-bit offsets.
832 needsLowering = ((Addr.Offset & 0xfff) != Addr.Offset);
833 // Handle negative offsets.
834 if (needsLowering && isThumb2)
835 needsLowering = !(Subtarget->hasV6T2Ops() && Addr.Offset < 0 &&
838 // ARM halfword load/stores and signed byte loads use +/-imm8 offsets.
839 needsLowering = (Addr.Offset > 255 || Addr.Offset < -255);
844 // Floating point operands handle 8-bit offsets.
845 needsLowering = ((Addr.Offset & 0xff) != Addr.Offset);
849 // If this is a stack pointer and the offset needs to be simplified then
850 // put the alloca address into a register, set the base type back to
851 // register and continue. This should almost never happen.
852 if (needsLowering && Addr.BaseType == Address::FrameIndexBase) {
853 const TargetRegisterClass *RC = isThumb2 ? &ARM::tGPRRegClass
855 unsigned ResultReg = createResultReg(RC);
856 unsigned Opc = isThumb2 ? ARM::t2ADDri : ARM::ADDri;
857 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
858 TII.get(Opc), ResultReg)
859 .addFrameIndex(Addr.Base.FI)
861 Addr.Base.Reg = ResultReg;
862 Addr.BaseType = Address::RegBase;
865 // Since the offset is too large for the load/store instruction
866 // get the reg+offset into a register.
868 Addr.Base.Reg = fastEmit_ri_(MVT::i32, ISD::ADD, Addr.Base.Reg,
869 /*Op0IsKill*/false, Addr.Offset, MVT::i32);
874 void ARMFastISel::AddLoadStoreOperands(MVT VT, Address &Addr,
875 const MachineInstrBuilder &MIB,
876 MachineMemOperand::Flags Flags,
878 // addrmode5 output depends on the selection dag addressing dividing the
879 // offset by 4 that it then later multiplies. Do this here as well.
880 if (VT.SimpleTy == MVT::f32 || VT.SimpleTy == MVT::f64)
883 // Frame base works a bit differently. Handle it separately.
884 if (Addr.BaseType == Address::FrameIndexBase) {
885 int FI = Addr.Base.FI;
886 int Offset = Addr.Offset;
887 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
888 MachinePointerInfo::getFixedStack(*FuncInfo.MF, FI, Offset), Flags,
889 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
890 // Now add the rest of the operands.
891 MIB.addFrameIndex(FI);
893 // ARM halfword load/stores and signed byte loads need an additional
896 int Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
900 MIB.addImm(Addr.Offset);
902 MIB.addMemOperand(MMO);
904 // Now add the rest of the operands.
905 MIB.addReg(Addr.Base.Reg);
907 // ARM halfword load/stores and signed byte loads need an additional
910 int Imm = (Addr.Offset < 0) ? (0x100 | -Addr.Offset) : Addr.Offset;
914 MIB.addImm(Addr.Offset);
917 AddOptionalDefs(MIB);
920 bool ARMFastISel::ARMEmitLoad(MVT VT, unsigned &ResultReg, Address &Addr,
921 unsigned Alignment, bool isZExt, bool allocReg) {
924 bool needVMOV = false;
925 const TargetRegisterClass *RC;
926 switch (VT.SimpleTy) {
927 // This is mostly going to be Neon/vector support.
928 default: return false;
932 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
933 Opc = isZExt ? ARM::t2LDRBi8 : ARM::t2LDRSBi8;
935 Opc = isZExt ? ARM::t2LDRBi12 : ARM::t2LDRSBi12;
944 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
947 if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
951 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
952 Opc = isZExt ? ARM::t2LDRHi8 : ARM::t2LDRSHi8;
954 Opc = isZExt ? ARM::t2LDRHi12 : ARM::t2LDRSHi12;
956 Opc = isZExt ? ARM::LDRH : ARM::LDRSH;
959 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
962 if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
966 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
973 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
976 if (!Subtarget->hasVFP2()) return false;
977 // Unaligned loads need special handling. Floats require word-alignment.
978 if (Alignment && Alignment < 4) {
981 Opc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
982 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRnopcRegClass;
985 RC = TLI.getRegClassFor(VT);
989 if (!Subtarget->hasVFP2()) return false;
990 // FIXME: Unaligned loads need special handling. Doublewords require
992 if (Alignment && Alignment < 4)
996 RC = TLI.getRegClassFor(VT);
999 // Simplify this down to something we can handle.
1000 ARMSimplifyAddress(Addr, VT, useAM3);
1002 // Create the base instruction, then add the operands.
1004 ResultReg = createResultReg(RC);
1005 assert (ResultReg > 255 && "Expected an allocated virtual register.");
1006 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1007 TII.get(Opc), ResultReg);
1008 AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOLoad, useAM3);
1010 // If we had an unaligned load of a float we've converted it to an regular
1011 // load. Now we must move from the GRP to the FP register.
1013 unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1014 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1015 TII.get(ARM::VMOVSR), MoveReg)
1016 .addReg(ResultReg));
1017 ResultReg = MoveReg;
1022 bool ARMFastISel::SelectLoad(const Instruction *I) {
1023 // Atomic loads need special handling.
1024 if (cast<LoadInst>(I)->isAtomic())
1027 const Value *SV = I->getOperand(0);
1028 if (TLI.supportSwiftError()) {
1029 // Swifterror values can come from either a function parameter with
1030 // swifterror attribute or an alloca with swifterror attribute.
1031 if (const Argument *Arg = dyn_cast<Argument>(SV)) {
1032 if (Arg->hasSwiftErrorAttr())
1036 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(SV)) {
1037 if (Alloca->isSwiftError())
1042 // Verify we have a legal type before going any further.
1044 if (!isLoadTypeLegal(I->getType(), VT))
1047 // See if we can handle this address.
1049 if (!ARMComputeAddress(I->getOperand(0), Addr)) return false;
1052 if (!ARMEmitLoad(VT, ResultReg, Addr, cast<LoadInst>(I)->getAlignment()))
1054 updateValueMap(I, ResultReg);
1058 bool ARMFastISel::ARMEmitStore(MVT VT, unsigned SrcReg, Address &Addr,
1059 unsigned Alignment) {
1061 bool useAM3 = false;
1062 switch (VT.SimpleTy) {
1063 // This is mostly going to be Neon/vector support.
1064 default: return false;
1066 unsigned Res = createResultReg(isThumb2 ? &ARM::tGPRRegClass
1067 : &ARM::GPRRegClass);
1068 unsigned Opc = isThumb2 ? ARM::t2ANDri : ARM::ANDri;
1069 SrcReg = constrainOperandRegClass(TII.get(Opc), SrcReg, 1);
1070 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1072 .addReg(SrcReg).addImm(1));
1074 } // Fallthrough here.
1077 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1078 StrOpc = ARM::t2STRBi8;
1080 StrOpc = ARM::t2STRBi12;
1082 StrOpc = ARM::STRBi12;
1086 if (Alignment && Alignment < 2 && !Subtarget->allowsUnalignedMem())
1090 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1091 StrOpc = ARM::t2STRHi8;
1093 StrOpc = ARM::t2STRHi12;
1100 if (Alignment && Alignment < 4 && !Subtarget->allowsUnalignedMem())
1104 if (Addr.Offset < 0 && Addr.Offset > -256 && Subtarget->hasV6T2Ops())
1105 StrOpc = ARM::t2STRi8;
1107 StrOpc = ARM::t2STRi12;
1109 StrOpc = ARM::STRi12;
1113 if (!Subtarget->hasVFP2()) return false;
1114 // Unaligned stores need special handling. Floats require word-alignment.
1115 if (Alignment && Alignment < 4) {
1116 unsigned MoveReg = createResultReg(TLI.getRegClassFor(MVT::i32));
1117 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1118 TII.get(ARM::VMOVRS), MoveReg)
1122 StrOpc = isThumb2 ? ARM::t2STRi12 : ARM::STRi12;
1124 StrOpc = ARM::VSTRS;
1128 if (!Subtarget->hasVFP2()) return false;
1129 // FIXME: Unaligned stores need special handling. Doublewords require
1131 if (Alignment && Alignment < 4)
1134 StrOpc = ARM::VSTRD;
1137 // Simplify this down to something we can handle.
1138 ARMSimplifyAddress(Addr, VT, useAM3);
1140 // Create the base instruction, then add the operands.
1141 SrcReg = constrainOperandRegClass(TII.get(StrOpc), SrcReg, 0);
1142 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1145 AddLoadStoreOperands(VT, Addr, MIB, MachineMemOperand::MOStore, useAM3);
1149 bool ARMFastISel::SelectStore(const Instruction *I) {
1150 Value *Op0 = I->getOperand(0);
1151 unsigned SrcReg = 0;
1153 // Atomic stores need special handling.
1154 if (cast<StoreInst>(I)->isAtomic())
1157 const Value *PtrV = I->getOperand(1);
1158 if (TLI.supportSwiftError()) {
1159 // Swifterror values can come from either a function parameter with
1160 // swifterror attribute or an alloca with swifterror attribute.
1161 if (const Argument *Arg = dyn_cast<Argument>(PtrV)) {
1162 if (Arg->hasSwiftErrorAttr())
1166 if (const AllocaInst *Alloca = dyn_cast<AllocaInst>(PtrV)) {
1167 if (Alloca->isSwiftError())
1172 // Verify we have a legal type before going any further.
1174 if (!isLoadTypeLegal(I->getOperand(0)->getType(), VT))
1177 // Get the value to be stored into a register.
1178 SrcReg = getRegForValue(Op0);
1179 if (SrcReg == 0) return false;
1181 // See if we can handle this address.
1183 if (!ARMComputeAddress(I->getOperand(1), Addr))
1186 if (!ARMEmitStore(VT, SrcReg, Addr, cast<StoreInst>(I)->getAlignment()))
1191 static ARMCC::CondCodes getComparePred(CmpInst::Predicate Pred) {
1193 // Needs two compares...
1194 case CmpInst::FCMP_ONE:
1195 case CmpInst::FCMP_UEQ:
1197 // AL is our "false" for now. The other two need more compares.
1199 case CmpInst::ICMP_EQ:
1200 case CmpInst::FCMP_OEQ:
1202 case CmpInst::ICMP_SGT:
1203 case CmpInst::FCMP_OGT:
1205 case CmpInst::ICMP_SGE:
1206 case CmpInst::FCMP_OGE:
1208 case CmpInst::ICMP_UGT:
1209 case CmpInst::FCMP_UGT:
1211 case CmpInst::FCMP_OLT:
1213 case CmpInst::ICMP_ULE:
1214 case CmpInst::FCMP_OLE:
1216 case CmpInst::FCMP_ORD:
1218 case CmpInst::FCMP_UNO:
1220 case CmpInst::FCMP_UGE:
1222 case CmpInst::ICMP_SLT:
1223 case CmpInst::FCMP_ULT:
1225 case CmpInst::ICMP_SLE:
1226 case CmpInst::FCMP_ULE:
1228 case CmpInst::FCMP_UNE:
1229 case CmpInst::ICMP_NE:
1231 case CmpInst::ICMP_UGE:
1233 case CmpInst::ICMP_ULT:
1238 bool ARMFastISel::SelectBranch(const Instruction *I) {
1239 const BranchInst *BI = cast<BranchInst>(I);
1240 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
1241 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
1243 // Simple branch support.
1245 // If we can, avoid recomputing the compare - redoing it could lead to wonky
1247 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
1248 if (CI->hasOneUse() && (CI->getParent() == I->getParent())) {
1250 // Get the compare predicate.
1251 // Try to take advantage of fallthrough opportunities.
1252 CmpInst::Predicate Predicate = CI->getPredicate();
1253 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1254 std::swap(TBB, FBB);
1255 Predicate = CmpInst::getInversePredicate(Predicate);
1258 ARMCC::CondCodes ARMPred = getComparePred(Predicate);
1260 // We may not handle every CC for now.
1261 if (ARMPred == ARMCC::AL) return false;
1263 // Emit the compare.
1264 if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1267 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1268 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1269 .addMBB(TBB).addImm(ARMPred).addReg(ARM::CPSR);
1270 finishCondBranch(BI->getParent(), TBB, FBB);
1273 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
1275 if (TI->hasOneUse() && TI->getParent() == I->getParent() &&
1276 (isLoadTypeLegal(TI->getOperand(0)->getType(), SourceVT))) {
1277 unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1278 unsigned OpReg = getRegForValue(TI->getOperand(0));
1279 OpReg = constrainOperandRegClass(TII.get(TstOpc), OpReg, 0);
1280 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1282 .addReg(OpReg).addImm(1));
1284 unsigned CCMode = ARMCC::NE;
1285 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1286 std::swap(TBB, FBB);
1290 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1291 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1292 .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1294 finishCondBranch(BI->getParent(), TBB, FBB);
1297 } else if (const ConstantInt *CI =
1298 dyn_cast<ConstantInt>(BI->getCondition())) {
1299 uint64_t Imm = CI->getZExtValue();
1300 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
1301 fastEmitBranch(Target, DbgLoc);
1305 unsigned CmpReg = getRegForValue(BI->getCondition());
1306 if (CmpReg == 0) return false;
1308 // We've been divorced from our compare! Our block was split, and
1309 // now our compare lives in a predecessor block. We musn't
1310 // re-compare here, as the children of the compare aren't guaranteed
1311 // live across the block boundary (we *could* check for this).
1312 // Regardless, the compare has been done in the predecessor block,
1313 // and it left a value for us in a virtual register. Ergo, we test
1314 // the one-bit value left in the virtual register.
1315 unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1316 CmpReg = constrainOperandRegClass(TII.get(TstOpc), CmpReg, 0);
1318 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TstOpc))
1322 unsigned CCMode = ARMCC::NE;
1323 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
1324 std::swap(TBB, FBB);
1328 unsigned BrOpc = isThumb2 ? ARM::t2Bcc : ARM::Bcc;
1329 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(BrOpc))
1330 .addMBB(TBB).addImm(CCMode).addReg(ARM::CPSR);
1331 finishCondBranch(BI->getParent(), TBB, FBB);
1335 bool ARMFastISel::SelectIndirectBr(const Instruction *I) {
1336 unsigned AddrReg = getRegForValue(I->getOperand(0));
1337 if (AddrReg == 0) return false;
1339 unsigned Opc = isThumb2 ? ARM::tBRIND : ARM::BX;
1340 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1341 TII.get(Opc)).addReg(AddrReg));
1343 const IndirectBrInst *IB = cast<IndirectBrInst>(I);
1344 for (const BasicBlock *SuccBB : IB->successors())
1345 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[SuccBB]);
1350 bool ARMFastISel::ARMEmitCmp(const Value *Src1Value, const Value *Src2Value,
1352 Type *Ty = Src1Value->getType();
1353 EVT SrcEVT = TLI.getValueType(DL, Ty, true);
1354 if (!SrcEVT.isSimple()) return false;
1355 MVT SrcVT = SrcEVT.getSimpleVT();
1357 bool isFloat = (Ty->isFloatTy() || Ty->isDoubleTy());
1358 if (isFloat && !Subtarget->hasVFP2())
1361 // Check to see if the 2nd operand is a constant that we can encode directly
1364 bool UseImm = false;
1365 bool isNegativeImm = false;
1366 // FIXME: At -O0 we don't have anything that canonicalizes operand order.
1367 // Thus, Src1Value may be a ConstantInt, but we're missing it.
1368 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(Src2Value)) {
1369 if (SrcVT == MVT::i32 || SrcVT == MVT::i16 || SrcVT == MVT::i8 ||
1371 const APInt &CIVal = ConstInt->getValue();
1372 Imm = (isZExt) ? (int)CIVal.getZExtValue() : (int)CIVal.getSExtValue();
1373 // For INT_MIN/LONG_MIN (i.e., 0x80000000) we need to use a cmp, rather
1374 // then a cmn, because there is no way to represent 2147483648 as a
1375 // signed 32-bit int.
1376 if (Imm < 0 && Imm != (int)0x80000000) {
1377 isNegativeImm = true;
1380 UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1381 (ARM_AM::getSOImmVal(Imm) != -1);
1383 } else if (const ConstantFP *ConstFP = dyn_cast<ConstantFP>(Src2Value)) {
1384 if (SrcVT == MVT::f32 || SrcVT == MVT::f64)
1385 if (ConstFP->isZero() && !ConstFP->isNegative())
1391 bool needsExt = false;
1392 switch (SrcVT.SimpleTy) {
1393 default: return false;
1394 // TODO: Verify compares.
1397 CmpOpc = UseImm ? ARM::VCMPEZS : ARM::VCMPES;
1401 CmpOpc = UseImm ? ARM::VCMPEZD : ARM::VCMPED;
1407 // Intentional fall-through.
1411 CmpOpc = ARM::t2CMPrr;
1413 CmpOpc = isNegativeImm ? ARM::t2CMNri : ARM::t2CMPri;
1416 CmpOpc = ARM::CMPrr;
1418 CmpOpc = isNegativeImm ? ARM::CMNri : ARM::CMPri;
1423 unsigned SrcReg1 = getRegForValue(Src1Value);
1424 if (SrcReg1 == 0) return false;
1426 unsigned SrcReg2 = 0;
1428 SrcReg2 = getRegForValue(Src2Value);
1429 if (SrcReg2 == 0) return false;
1432 // We have i1, i8, or i16, we need to either zero extend or sign extend.
1434 SrcReg1 = ARMEmitIntExt(SrcVT, SrcReg1, MVT::i32, isZExt);
1435 if (SrcReg1 == 0) return false;
1437 SrcReg2 = ARMEmitIntExt(SrcVT, SrcReg2, MVT::i32, isZExt);
1438 if (SrcReg2 == 0) return false;
1442 const MCInstrDesc &II = TII.get(CmpOpc);
1443 SrcReg1 = constrainOperandRegClass(II, SrcReg1, 0);
1445 SrcReg2 = constrainOperandRegClass(II, SrcReg2, 1);
1446 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1447 .addReg(SrcReg1).addReg(SrcReg2));
1449 MachineInstrBuilder MIB;
1450 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II)
1453 // Only add immediate for icmp as the immediate for fcmp is an implicit 0.0.
1456 AddOptionalDefs(MIB);
1459 // For floating point we need to move the result to a comparison register
1460 // that we can then use for branches.
1461 if (Ty->isFloatTy() || Ty->isDoubleTy())
1462 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1463 TII.get(ARM::FMSTAT)));
1467 bool ARMFastISel::SelectCmp(const Instruction *I) {
1468 const CmpInst *CI = cast<CmpInst>(I);
1470 // Get the compare predicate.
1471 ARMCC::CondCodes ARMPred = getComparePred(CI->getPredicate());
1473 // We may not handle every CC for now.
1474 if (ARMPred == ARMCC::AL) return false;
1476 // Emit the compare.
1477 if (!ARMEmitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
1480 // Now set a register based on the comparison. Explicitly set the predicates
1482 unsigned MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1483 const TargetRegisterClass *RC = isThumb2 ? &ARM::rGPRRegClass
1484 : &ARM::GPRRegClass;
1485 unsigned DestReg = createResultReg(RC);
1486 Constant *Zero = ConstantInt::get(Type::getInt32Ty(*Context), 0);
1487 unsigned ZeroReg = fastMaterializeConstant(Zero);
1488 // ARMEmitCmp emits a FMSTAT when necessary, so it's always safe to use CPSR.
1489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc), DestReg)
1490 .addReg(ZeroReg).addImm(1)
1491 .addImm(ARMPred).addReg(ARM::CPSR);
1493 updateValueMap(I, DestReg);
1497 bool ARMFastISel::SelectFPExt(const Instruction *I) {
1498 // Make sure we have VFP and that we're extending float to double.
1499 if (!Subtarget->hasVFP2()) return false;
1501 Value *V = I->getOperand(0);
1502 if (!I->getType()->isDoubleTy() ||
1503 !V->getType()->isFloatTy()) return false;
1505 unsigned Op = getRegForValue(V);
1506 if (Op == 0) return false;
1508 unsigned Result = createResultReg(&ARM::DPRRegClass);
1509 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1510 TII.get(ARM::VCVTDS), Result)
1512 updateValueMap(I, Result);
1516 bool ARMFastISel::SelectFPTrunc(const Instruction *I) {
1517 // Make sure we have VFP and that we're truncating double to float.
1518 if (!Subtarget->hasVFP2()) return false;
1520 Value *V = I->getOperand(0);
1521 if (!(I->getType()->isFloatTy() &&
1522 V->getType()->isDoubleTy())) return false;
1524 unsigned Op = getRegForValue(V);
1525 if (Op == 0) return false;
1527 unsigned Result = createResultReg(&ARM::SPRRegClass);
1528 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1529 TII.get(ARM::VCVTSD), Result)
1531 updateValueMap(I, Result);
1535 bool ARMFastISel::SelectIToFP(const Instruction *I, bool isSigned) {
1536 // Make sure we have VFP.
1537 if (!Subtarget->hasVFP2()) return false;
1540 Type *Ty = I->getType();
1541 if (!isTypeLegal(Ty, DstVT))
1544 Value *Src = I->getOperand(0);
1545 EVT SrcEVT = TLI.getValueType(DL, Src->getType(), true);
1546 if (!SrcEVT.isSimple())
1548 MVT SrcVT = SrcEVT.getSimpleVT();
1549 if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
1552 unsigned SrcReg = getRegForValue(Src);
1553 if (SrcReg == 0) return false;
1555 // Handle sign-extension.
1556 if (SrcVT == MVT::i16 || SrcVT == MVT::i8) {
1557 SrcReg = ARMEmitIntExt(SrcVT, SrcReg, MVT::i32,
1558 /*isZExt*/!isSigned);
1559 if (SrcReg == 0) return false;
1562 // The conversion routine works on fp-reg to fp-reg and the operand above
1563 // was an integer, move it to the fp registers if possible.
1564 unsigned FP = ARMMoveToFPReg(MVT::f32, SrcReg);
1565 if (FP == 0) return false;
1568 if (Ty->isFloatTy()) Opc = isSigned ? ARM::VSITOS : ARM::VUITOS;
1569 else if (Ty->isDoubleTy()) Opc = isSigned ? ARM::VSITOD : ARM::VUITOD;
1572 unsigned ResultReg = createResultReg(TLI.getRegClassFor(DstVT));
1573 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1574 TII.get(Opc), ResultReg).addReg(FP));
1575 updateValueMap(I, ResultReg);
1579 bool ARMFastISel::SelectFPToI(const Instruction *I, bool isSigned) {
1580 // Make sure we have VFP.
1581 if (!Subtarget->hasVFP2()) return false;
1584 Type *RetTy = I->getType();
1585 if (!isTypeLegal(RetTy, DstVT))
1588 unsigned Op = getRegForValue(I->getOperand(0));
1589 if (Op == 0) return false;
1592 Type *OpTy = I->getOperand(0)->getType();
1593 if (OpTy->isFloatTy()) Opc = isSigned ? ARM::VTOSIZS : ARM::VTOUIZS;
1594 else if (OpTy->isDoubleTy()) Opc = isSigned ? ARM::VTOSIZD : ARM::VTOUIZD;
1597 // f64->s32/u32 or f32->s32/u32 both need an intermediate f32 reg.
1598 unsigned ResultReg = createResultReg(TLI.getRegClassFor(MVT::f32));
1599 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1600 TII.get(Opc), ResultReg).addReg(Op));
1602 // This result needs to be in an integer register, but the conversion only
1603 // takes place in fp-regs.
1604 unsigned IntReg = ARMMoveToIntReg(DstVT, ResultReg);
1605 if (IntReg == 0) return false;
1607 updateValueMap(I, IntReg);
1611 bool ARMFastISel::SelectSelect(const Instruction *I) {
1613 if (!isTypeLegal(I->getType(), VT))
1616 // Things need to be register sized for register moves.
1617 if (VT != MVT::i32) return false;
1619 unsigned CondReg = getRegForValue(I->getOperand(0));
1620 if (CondReg == 0) return false;
1621 unsigned Op1Reg = getRegForValue(I->getOperand(1));
1622 if (Op1Reg == 0) return false;
1624 // Check to see if we can use an immediate in the conditional move.
1626 bool UseImm = false;
1627 bool isNegativeImm = false;
1628 if (const ConstantInt *ConstInt = dyn_cast<ConstantInt>(I->getOperand(2))) {
1629 assert (VT == MVT::i32 && "Expecting an i32.");
1630 Imm = (int)ConstInt->getValue().getZExtValue();
1632 isNegativeImm = true;
1635 UseImm = isThumb2 ? (ARM_AM::getT2SOImmVal(Imm) != -1) :
1636 (ARM_AM::getSOImmVal(Imm) != -1);
1639 unsigned Op2Reg = 0;
1641 Op2Reg = getRegForValue(I->getOperand(2));
1642 if (Op2Reg == 0) return false;
1645 unsigned TstOpc = isThumb2 ? ARM::t2TSTri : ARM::TSTri;
1646 CondReg = constrainOperandRegClass(TII.get(TstOpc), CondReg, 0);
1648 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TstOpc))
1653 const TargetRegisterClass *RC;
1655 RC = isThumb2 ? &ARM::tGPRRegClass : &ARM::GPRRegClass;
1656 MovCCOpc = isThumb2 ? ARM::t2MOVCCr : ARM::MOVCCr;
1658 RC = isThumb2 ? &ARM::rGPRRegClass : &ARM::GPRRegClass;
1660 MovCCOpc = isThumb2 ? ARM::t2MOVCCi : ARM::MOVCCi;
1662 MovCCOpc = isThumb2 ? ARM::t2MVNCCi : ARM::MVNCCi;
1664 unsigned ResultReg = createResultReg(RC);
1666 Op2Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op2Reg, 1);
1667 Op1Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op1Reg, 2);
1668 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc),
1675 Op1Reg = constrainOperandRegClass(TII.get(MovCCOpc), Op1Reg, 1);
1676 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(MovCCOpc),
1683 updateValueMap(I, ResultReg);
1687 bool ARMFastISel::SelectDiv(const Instruction *I, bool isSigned) {
1689 Type *Ty = I->getType();
1690 if (!isTypeLegal(Ty, VT))
1693 // If we have integer div support we should have selected this automagically.
1694 // In case we have a real miss go ahead and return false and we'll pick
1696 if (Subtarget->hasDivide()) return false;
1698 // Otherwise emit a libcall.
1699 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1701 LC = isSigned ? RTLIB::SDIV_I8 : RTLIB::UDIV_I8;
1702 else if (VT == MVT::i16)
1703 LC = isSigned ? RTLIB::SDIV_I16 : RTLIB::UDIV_I16;
1704 else if (VT == MVT::i32)
1705 LC = isSigned ? RTLIB::SDIV_I32 : RTLIB::UDIV_I32;
1706 else if (VT == MVT::i64)
1707 LC = isSigned ? RTLIB::SDIV_I64 : RTLIB::UDIV_I64;
1708 else if (VT == MVT::i128)
1709 LC = isSigned ? RTLIB::SDIV_I128 : RTLIB::UDIV_I128;
1710 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
1712 return ARMEmitLibcall(I, LC);
1715 bool ARMFastISel::SelectRem(const Instruction *I, bool isSigned) {
1717 Type *Ty = I->getType();
1718 if (!isTypeLegal(Ty, VT))
1721 // Many ABIs do not provide a libcall for standalone remainder, so we need to
1722 // use divrem (see the RTABI 4.3.1). Since FastISel can't handle non-double
1723 // multi-reg returns, we'll have to bail out.
1724 if (!TLI.hasStandaloneRem(VT)) {
1728 RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1730 LC = isSigned ? RTLIB::SREM_I8 : RTLIB::UREM_I8;
1731 else if (VT == MVT::i16)
1732 LC = isSigned ? RTLIB::SREM_I16 : RTLIB::UREM_I16;
1733 else if (VT == MVT::i32)
1734 LC = isSigned ? RTLIB::SREM_I32 : RTLIB::UREM_I32;
1735 else if (VT == MVT::i64)
1736 LC = isSigned ? RTLIB::SREM_I64 : RTLIB::UREM_I64;
1737 else if (VT == MVT::i128)
1738 LC = isSigned ? RTLIB::SREM_I128 : RTLIB::UREM_I128;
1739 assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
1741 return ARMEmitLibcall(I, LC);
1744 bool ARMFastISel::SelectBinaryIntOp(const Instruction *I, unsigned ISDOpcode) {
1745 EVT DestVT = TLI.getValueType(DL, I->getType(), true);
1747 // We can get here in the case when we have a binary operation on a non-legal
1748 // type and the target independent selector doesn't know how to handle it.
1749 if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
1753 switch (ISDOpcode) {
1754 default: return false;
1756 Opc = isThumb2 ? ARM::t2ADDrr : ARM::ADDrr;
1759 Opc = isThumb2 ? ARM::t2ORRrr : ARM::ORRrr;
1762 Opc = isThumb2 ? ARM::t2SUBrr : ARM::SUBrr;
1766 unsigned SrcReg1 = getRegForValue(I->getOperand(0));
1767 if (SrcReg1 == 0) return false;
1769 // TODO: Often the 2nd operand is an immediate, which can be encoded directly
1770 // in the instruction, rather then materializing the value in a register.
1771 unsigned SrcReg2 = getRegForValue(I->getOperand(1));
1772 if (SrcReg2 == 0) return false;
1774 unsigned ResultReg = createResultReg(&ARM::GPRnopcRegClass);
1775 SrcReg1 = constrainOperandRegClass(TII.get(Opc), SrcReg1, 1);
1776 SrcReg2 = constrainOperandRegClass(TII.get(Opc), SrcReg2, 2);
1777 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1778 TII.get(Opc), ResultReg)
1779 .addReg(SrcReg1).addReg(SrcReg2));
1780 updateValueMap(I, ResultReg);
1784 bool ARMFastISel::SelectBinaryFPOp(const Instruction *I, unsigned ISDOpcode) {
1785 EVT FPVT = TLI.getValueType(DL, I->getType(), true);
1786 if (!FPVT.isSimple()) return false;
1787 MVT VT = FPVT.getSimpleVT();
1789 // FIXME: Support vector types where possible.
1793 // We can get here in the case when we want to use NEON for our fp
1794 // operations, but can't figure out how to. Just use the vfp instructions
1796 // FIXME: It'd be nice to use NEON instructions.
1797 Type *Ty = I->getType();
1798 bool isFloat = (Ty->isDoubleTy() || Ty->isFloatTy());
1799 if (isFloat && !Subtarget->hasVFP2())
1803 bool is64bit = VT == MVT::f64 || VT == MVT::i64;
1804 switch (ISDOpcode) {
1805 default: return false;
1807 Opc = is64bit ? ARM::VADDD : ARM::VADDS;
1810 Opc = is64bit ? ARM::VSUBD : ARM::VSUBS;
1813 Opc = is64bit ? ARM::VMULD : ARM::VMULS;
1816 unsigned Op1 = getRegForValue(I->getOperand(0));
1817 if (Op1 == 0) return false;
1819 unsigned Op2 = getRegForValue(I->getOperand(1));
1820 if (Op2 == 0) return false;
1822 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT.SimpleTy));
1823 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1824 TII.get(Opc), ResultReg)
1825 .addReg(Op1).addReg(Op2));
1826 updateValueMap(I, ResultReg);
1830 // Call Handling Code
1832 // This is largely taken directly from CCAssignFnForNode
1833 // TODO: We may not support all of this.
1834 CCAssignFn *ARMFastISel::CCAssignFnForCall(CallingConv::ID CC,
1839 llvm_unreachable("Unsupported calling convention");
1840 case CallingConv::Fast:
1841 if (Subtarget->hasVFP2() && !isVarArg) {
1842 if (!Subtarget->isAAPCS_ABI())
1843 return (Return ? RetFastCC_ARM_APCS : FastCC_ARM_APCS);
1844 // For AAPCS ABI targets, just use VFP variant of the calling convention.
1845 return (Return ? RetCC_ARM_AAPCS_VFP : CC_ARM_AAPCS_VFP);
1848 case CallingConv::C:
1849 case CallingConv::CXX_FAST_TLS:
1850 // Use target triple & subtarget features to do actual dispatch.
1851 if (Subtarget->isAAPCS_ABI()) {
1852 if (Subtarget->hasVFP2() &&
1853 TM.Options.FloatABIType == FloatABI::Hard && !isVarArg)
1854 return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1856 return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1858 return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1860 case CallingConv::ARM_AAPCS_VFP:
1861 case CallingConv::Swift:
1863 return (Return ? RetCC_ARM_AAPCS_VFP: CC_ARM_AAPCS_VFP);
1864 // Fall through to soft float variant, variadic functions don't
1865 // use hard floating point ABI.
1866 case CallingConv::ARM_AAPCS:
1867 return (Return ? RetCC_ARM_AAPCS: CC_ARM_AAPCS);
1868 case CallingConv::ARM_APCS:
1869 return (Return ? RetCC_ARM_APCS: CC_ARM_APCS);
1870 case CallingConv::GHC:
1872 llvm_unreachable("Can't return in GHC call convention");
1874 return CC_ARM_APCS_GHC;
1878 bool ARMFastISel::ProcessCallArgs(SmallVectorImpl<Value*> &Args,
1879 SmallVectorImpl<unsigned> &ArgRegs,
1880 SmallVectorImpl<MVT> &ArgVTs,
1881 SmallVectorImpl<ISD::ArgFlagsTy> &ArgFlags,
1882 SmallVectorImpl<unsigned> &RegArgs,
1886 SmallVector<CCValAssign, 16> ArgLocs;
1887 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, ArgLocs, *Context);
1888 CCInfo.AnalyzeCallOperands(ArgVTs, ArgFlags,
1889 CCAssignFnForCall(CC, false, isVarArg));
1891 // Check that we can handle all of the arguments. If we can't, then bail out
1892 // now before we add code to the MBB.
1893 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1894 CCValAssign &VA = ArgLocs[i];
1895 MVT ArgVT = ArgVTs[VA.getValNo()];
1897 // We don't handle NEON/vector parameters yet.
1898 if (ArgVT.isVector() || ArgVT.getSizeInBits() > 64)
1901 // Now copy/store arg to correct locations.
1902 if (VA.isRegLoc() && !VA.needsCustom()) {
1904 } else if (VA.needsCustom()) {
1905 // TODO: We need custom lowering for vector (v2f64) args.
1906 if (VA.getLocVT() != MVT::f64 ||
1907 // TODO: Only handle register args for now.
1908 !VA.isRegLoc() || !ArgLocs[++i].isRegLoc())
1911 switch (ArgVT.SimpleTy) {
1920 if (!Subtarget->hasVFP2())
1924 if (!Subtarget->hasVFP2())
1931 // At the point, we are able to handle the call's arguments in fast isel.
1933 // Get a count of how many bytes are to be pushed on the stack.
1934 NumBytes = CCInfo.getNextStackOffset();
1936 // Issue CALLSEQ_START
1937 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
1938 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1939 TII.get(AdjStackDown))
1942 // Process the args.
1943 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
1944 CCValAssign &VA = ArgLocs[i];
1945 const Value *ArgVal = Args[VA.getValNo()];
1946 unsigned Arg = ArgRegs[VA.getValNo()];
1947 MVT ArgVT = ArgVTs[VA.getValNo()];
1949 assert((!ArgVT.isVector() && ArgVT.getSizeInBits() <= 64) &&
1950 "We don't handle NEON/vector parameters yet.");
1952 // Handle arg promotion, etc.
1953 switch (VA.getLocInfo()) {
1954 case CCValAssign::Full: break;
1955 case CCValAssign::SExt: {
1956 MVT DestVT = VA.getLocVT();
1957 Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/false);
1958 assert (Arg != 0 && "Failed to emit a sext");
1962 case CCValAssign::AExt:
1963 // Intentional fall-through. Handle AExt and ZExt.
1964 case CCValAssign::ZExt: {
1965 MVT DestVT = VA.getLocVT();
1966 Arg = ARMEmitIntExt(ArgVT, Arg, DestVT, /*isZExt*/true);
1967 assert (Arg != 0 && "Failed to emit a zext");
1971 case CCValAssign::BCvt: {
1972 unsigned BC = fastEmit_r(ArgVT, VA.getLocVT(), ISD::BITCAST, Arg,
1973 /*TODO: Kill=*/false);
1974 assert(BC != 0 && "Failed to emit a bitcast!");
1976 ArgVT = VA.getLocVT();
1979 default: llvm_unreachable("Unknown arg promotion!");
1982 // Now copy/store arg to correct locations.
1983 if (VA.isRegLoc() && !VA.needsCustom()) {
1984 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1985 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(Arg);
1986 RegArgs.push_back(VA.getLocReg());
1987 } else if (VA.needsCustom()) {
1988 // TODO: We need custom lowering for vector (v2f64) args.
1989 assert(VA.getLocVT() == MVT::f64 &&
1990 "Custom lowering for v2f64 args not available");
1992 CCValAssign &NextVA = ArgLocs[++i];
1994 assert(VA.isRegLoc() && NextVA.isRegLoc() &&
1995 "We only handle register args!");
1997 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1998 TII.get(ARM::VMOVRRD), VA.getLocReg())
1999 .addReg(NextVA.getLocReg(), RegState::Define)
2001 RegArgs.push_back(VA.getLocReg());
2002 RegArgs.push_back(NextVA.getLocReg());
2004 assert(VA.isMemLoc());
2005 // Need to store on the stack.
2007 // Don't emit stores for undef values.
2008 if (isa<UndefValue>(ArgVal))
2012 Addr.BaseType = Address::RegBase;
2013 Addr.Base.Reg = ARM::SP;
2014 Addr.Offset = VA.getLocMemOffset();
2016 bool EmitRet = ARMEmitStore(ArgVT, Arg, Addr); (void)EmitRet;
2017 assert(EmitRet && "Could not emit a store for argument!");
2024 bool ARMFastISel::FinishCall(MVT RetVT, SmallVectorImpl<unsigned> &UsedRegs,
2025 const Instruction *I, CallingConv::ID CC,
2026 unsigned &NumBytes, bool isVarArg) {
2027 // Issue CALLSEQ_END
2028 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2029 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2030 TII.get(AdjStackUp))
2031 .addImm(NumBytes).addImm(0));
2033 // Now the return value.
2034 if (RetVT != MVT::isVoid) {
2035 SmallVector<CCValAssign, 16> RVLocs;
2036 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, RVLocs, *Context);
2037 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2039 // Copy all of the result registers out of their specified physreg.
2040 if (RVLocs.size() == 2 && RetVT == MVT::f64) {
2041 // For this move we copy into two registers and then move into the
2042 // double fp reg we want.
2043 MVT DestVT = RVLocs[0].getValVT();
2044 const TargetRegisterClass* DstRC = TLI.getRegClassFor(DestVT);
2045 unsigned ResultReg = createResultReg(DstRC);
2046 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2047 TII.get(ARM::VMOVDRR), ResultReg)
2048 .addReg(RVLocs[0].getLocReg())
2049 .addReg(RVLocs[1].getLocReg()));
2051 UsedRegs.push_back(RVLocs[0].getLocReg());
2052 UsedRegs.push_back(RVLocs[1].getLocReg());
2054 // Finally update the result.
2055 updateValueMap(I, ResultReg);
2057 assert(RVLocs.size() == 1 &&"Can't handle non-double multi-reg retvals!");
2058 MVT CopyVT = RVLocs[0].getValVT();
2060 // Special handling for extended integers.
2061 if (RetVT == MVT::i1 || RetVT == MVT::i8 || RetVT == MVT::i16)
2064 const TargetRegisterClass* DstRC = TLI.getRegClassFor(CopyVT);
2066 unsigned ResultReg = createResultReg(DstRC);
2067 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2068 TII.get(TargetOpcode::COPY),
2069 ResultReg).addReg(RVLocs[0].getLocReg());
2070 UsedRegs.push_back(RVLocs[0].getLocReg());
2072 // Finally update the result.
2073 updateValueMap(I, ResultReg);
2080 bool ARMFastISel::SelectRet(const Instruction *I) {
2081 const ReturnInst *Ret = cast<ReturnInst>(I);
2082 const Function &F = *I->getParent()->getParent();
2084 if (!FuncInfo.CanLowerReturn)
2087 if (TLI.supportSwiftError() &&
2088 F.getAttributes().hasAttrSomewhere(Attribute::SwiftError))
2091 if (TLI.supportSplitCSR(FuncInfo.MF))
2094 // Build a list of return value registers.
2095 SmallVector<unsigned, 4> RetRegs;
2097 CallingConv::ID CC = F.getCallingConv();
2098 if (Ret->getNumOperands() > 0) {
2099 SmallVector<ISD::OutputArg, 4> Outs;
2100 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI, DL);
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 */,
2108 const Value *RV = Ret->getOperand(0);
2109 unsigned Reg = getRegForValue(RV);
2113 // Only handle a single return value for now.
2114 if (ValLocs.size() != 1)
2117 CCValAssign &VA = ValLocs[0];
2119 // Don't bother handling odd stuff for now.
2120 if (VA.getLocInfo() != CCValAssign::Full)
2122 // Only handle register returns for now.
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)
2136 assert(DestVT == MVT::i32 && "ARM should always ext to i32");
2138 // Perform extension if flagged as either zext or sext. Otherwise, do
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;
2147 unsigned 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))
2152 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2153 TII.get(TargetOpcode::COPY), DstReg).addReg(SrcReg);
2155 // Add register to return instruction.
2156 RetRegs.push_back(VA.getLocReg());
2159 unsigned RetOpc = isThumb2 ? ARM::tBX_RET : ARM::BX_RET;
2160 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2162 AddOptionalDefs(MIB);
2163 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
2164 MIB.addReg(RetRegs[i], RegState::Implicit);
2168 unsigned ARMFastISel::ARMSelectCallOp(bool UseReg) {
2170 return isThumb2 ? ARM::tBLXr : ARM::BLX;
2172 return isThumb2 ? ARM::tBL : ARM::BL;
2175 unsigned ARMFastISel::getLibcallReg(const Twine &Name) {
2176 // Manually compute the global's type to avoid building it when unnecessary.
2177 Type *GVTy = Type::getInt32PtrTy(*Context, /*AS=*/0);
2178 EVT LCREVT = TLI.getValueType(DL, GVTy);
2179 if (!LCREVT.isSimple()) return 0;
2181 GlobalValue *GV = new GlobalVariable(M, Type::getInt32Ty(*Context), false,
2182 GlobalValue::ExternalLinkage, nullptr,
2184 assert(GV->getType() == GVTy && "We miscomputed the type for the global!");
2185 return ARMMaterializeGV(GV, LCREVT.getSimpleVT());
2188 // A quick function that will emit a call for a named libcall in F with the
2189 // vector of passed arguments for the Instruction in I. We can assume that we
2190 // can emit a call for any libcall we can produce. This is an abridged version
2191 // of the full call infrastructure since we won't need to worry about things
2192 // like computed function pointers or strange arguments at call sites.
2193 // TODO: Try to unify this and the normal call bits for ARM, then try to unify
2195 bool ARMFastISel::ARMEmitLibcall(const Instruction *I, RTLIB::Libcall Call) {
2196 CallingConv::ID CC = TLI.getLibcallCallingConv(Call);
2198 // Handle *simple* calls for now.
2199 Type *RetTy = I->getType();
2201 if (RetTy->isVoidTy())
2202 RetVT = MVT::isVoid;
2203 else if (!isTypeLegal(RetTy, RetVT))
2206 // Can't handle non-double multi-reg retvals.
2207 if (RetVT != MVT::isVoid && RetVT != MVT::i32) {
2208 SmallVector<CCValAssign, 16> RVLocs;
2209 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2210 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, false));
2211 if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2215 // Set up the argument vectors.
2216 SmallVector<Value*, 8> Args;
2217 SmallVector<unsigned, 8> ArgRegs;
2218 SmallVector<MVT, 8> ArgVTs;
2219 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2220 Args.reserve(I->getNumOperands());
2221 ArgRegs.reserve(I->getNumOperands());
2222 ArgVTs.reserve(I->getNumOperands());
2223 ArgFlags.reserve(I->getNumOperands());
2224 for (unsigned i = 0; i < I->getNumOperands(); ++i) {
2225 Value *Op = I->getOperand(i);
2226 unsigned Arg = getRegForValue(Op);
2227 if (Arg == 0) return false;
2229 Type *ArgTy = Op->getType();
2231 if (!isTypeLegal(ArgTy, ArgVT)) return false;
2233 ISD::ArgFlagsTy Flags;
2234 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2235 Flags.setOrigAlign(OriginalAlignment);
2238 ArgRegs.push_back(Arg);
2239 ArgVTs.push_back(ArgVT);
2240 ArgFlags.push_back(Flags);
2243 // Handle the arguments now that we've gotten them.
2244 SmallVector<unsigned, 4> RegArgs;
2246 if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2247 RegArgs, CC, NumBytes, false))
2250 unsigned CalleeReg = 0;
2251 if (Subtarget->genLongCalls()) {
2252 CalleeReg = getLibcallReg(TLI.getLibcallName(Call));
2253 if (CalleeReg == 0) return false;
2257 unsigned CallOpc = ARMSelectCallOp(Subtarget->genLongCalls());
2258 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2259 DbgLoc, TII.get(CallOpc));
2260 // BL / BLX don't take a predicate, but tBL / tBLX do.
2262 AddDefaultPred(MIB);
2263 if (Subtarget->genLongCalls())
2264 MIB.addReg(CalleeReg);
2266 MIB.addExternalSymbol(TLI.getLibcallName(Call));
2268 // Add implicit physical register uses to the call.
2269 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2270 MIB.addReg(RegArgs[i], RegState::Implicit);
2272 // Add a register mask with the call-preserved registers.
2273 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2274 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
2276 // Finish off the call including any return values.
2277 SmallVector<unsigned, 4> UsedRegs;
2278 if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, false)) return false;
2280 // Set all unused physreg defs as dead.
2281 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2286 bool ARMFastISel::SelectCall(const Instruction *I,
2287 const char *IntrMemName = nullptr) {
2288 const CallInst *CI = cast<CallInst>(I);
2289 const Value *Callee = CI->getCalledValue();
2291 // Can't handle inline asm.
2292 if (isa<InlineAsm>(Callee)) return false;
2294 // Allow SelectionDAG isel to handle tail calls.
2295 if (CI->isTailCall()) return false;
2297 // Check the calling convention.
2298 ImmutableCallSite CS(CI);
2299 CallingConv::ID CC = CS.getCallingConv();
2301 // TODO: Avoid some calling conventions?
2303 FunctionType *FTy = CS.getFunctionType();
2304 bool isVarArg = FTy->isVarArg();
2306 // Handle *simple* calls for now.
2307 Type *RetTy = I->getType();
2309 if (RetTy->isVoidTy())
2310 RetVT = MVT::isVoid;
2311 else if (!isTypeLegal(RetTy, RetVT) && RetVT != MVT::i16 &&
2312 RetVT != MVT::i8 && RetVT != MVT::i1)
2315 // Can't handle non-double multi-reg retvals.
2316 if (RetVT != MVT::isVoid && RetVT != MVT::i1 && RetVT != MVT::i8 &&
2317 RetVT != MVT::i16 && RetVT != MVT::i32) {
2318 SmallVector<CCValAssign, 16> RVLocs;
2319 CCState CCInfo(CC, isVarArg, *FuncInfo.MF, RVLocs, *Context);
2320 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC, true, isVarArg));
2321 if (RVLocs.size() >= 2 && RetVT != MVT::f64)
2325 // Set up the argument vectors.
2326 SmallVector<Value*, 8> Args;
2327 SmallVector<unsigned, 8> ArgRegs;
2328 SmallVector<MVT, 8> ArgVTs;
2329 SmallVector<ISD::ArgFlagsTy, 8> ArgFlags;
2330 unsigned arg_size = CS.arg_size();
2331 Args.reserve(arg_size);
2332 ArgRegs.reserve(arg_size);
2333 ArgVTs.reserve(arg_size);
2334 ArgFlags.reserve(arg_size);
2335 for (ImmutableCallSite::arg_iterator i = CS.arg_begin(), e = CS.arg_end();
2337 // If we're lowering a memory intrinsic instead of a regular call, skip the
2338 // last two arguments, which shouldn't be passed to the underlying function.
2339 if (IntrMemName && e-i <= 2)
2342 ISD::ArgFlagsTy Flags;
2343 unsigned AttrInd = i - CS.arg_begin() + 1;
2344 if (CS.paramHasAttr(AttrInd, Attribute::SExt))
2346 if (CS.paramHasAttr(AttrInd, Attribute::ZExt))
2349 // FIXME: Only handle *easy* calls for now.
2350 if (CS.paramHasAttr(AttrInd, Attribute::InReg) ||
2351 CS.paramHasAttr(AttrInd, Attribute::StructRet) ||
2352 CS.paramHasAttr(AttrInd, Attribute::SwiftSelf) ||
2353 CS.paramHasAttr(AttrInd, Attribute::SwiftError) ||
2354 CS.paramHasAttr(AttrInd, Attribute::Nest) ||
2355 CS.paramHasAttr(AttrInd, Attribute::ByVal))
2358 Type *ArgTy = (*i)->getType();
2360 if (!isTypeLegal(ArgTy, ArgVT) && ArgVT != MVT::i16 && ArgVT != MVT::i8 &&
2364 unsigned Arg = getRegForValue(*i);
2368 unsigned OriginalAlignment = DL.getABITypeAlignment(ArgTy);
2369 Flags.setOrigAlign(OriginalAlignment);
2372 ArgRegs.push_back(Arg);
2373 ArgVTs.push_back(ArgVT);
2374 ArgFlags.push_back(Flags);
2377 // Handle the arguments now that we've gotten them.
2378 SmallVector<unsigned, 4> RegArgs;
2380 if (!ProcessCallArgs(Args, ArgRegs, ArgVTs, ArgFlags,
2381 RegArgs, CC, NumBytes, isVarArg))
2384 bool UseReg = false;
2385 const GlobalValue *GV = dyn_cast<GlobalValue>(Callee);
2386 if (!GV || Subtarget->genLongCalls()) UseReg = true;
2388 unsigned CalleeReg = 0;
2391 CalleeReg = getLibcallReg(IntrMemName);
2393 CalleeReg = getRegForValue(Callee);
2395 if (CalleeReg == 0) return false;
2399 unsigned CallOpc = ARMSelectCallOp(UseReg);
2400 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt,
2401 DbgLoc, TII.get(CallOpc));
2403 // ARM calls don't take a predicate, but tBL / tBLX do.
2405 AddDefaultPred(MIB);
2407 MIB.addReg(CalleeReg);
2408 else if (!IntrMemName)
2409 MIB.addGlobalAddress(GV, 0, 0);
2411 MIB.addExternalSymbol(IntrMemName, 0);
2413 // Add implicit physical register uses to the call.
2414 for (unsigned i = 0, e = RegArgs.size(); i != e; ++i)
2415 MIB.addReg(RegArgs[i], RegState::Implicit);
2417 // Add a register mask with the call-preserved registers.
2418 // Proper defs for return values will be added by setPhysRegsDeadExcept().
2419 MIB.addRegMask(TRI.getCallPreservedMask(*FuncInfo.MF, CC));
2421 // Finish off the call including any return values.
2422 SmallVector<unsigned, 4> UsedRegs;
2423 if (!FinishCall(RetVT, UsedRegs, I, CC, NumBytes, isVarArg))
2426 // Set all unused physreg defs as dead.
2427 static_cast<MachineInstr *>(MIB)->setPhysRegsDeadExcept(UsedRegs, TRI);
2432 bool ARMFastISel::ARMIsMemCpySmall(uint64_t Len) {
2436 bool ARMFastISel::ARMTryEmitSmallMemCpy(Address Dest, Address Src,
2437 uint64_t Len, unsigned Alignment) {
2438 // Make sure we don't bloat code by inlining very large memcpy's.
2439 if (!ARMIsMemCpySmall(Len))
2444 if (!Alignment || Alignment >= 4) {
2450 assert (Len == 1 && "Expected a length of 1!");
2454 // Bound based on alignment.
2455 if (Len >= 2 && Alignment == 2)
2464 RV = ARMEmitLoad(VT, ResultReg, Src);
2465 assert (RV == true && "Should be able to handle this load.");
2466 RV = ARMEmitStore(VT, ResultReg, Dest);
2467 assert (RV == true && "Should be able to handle this store.");
2470 unsigned Size = VT.getSizeInBits()/8;
2472 Dest.Offset += Size;
2479 bool ARMFastISel::SelectIntrinsicCall(const IntrinsicInst &I) {
2480 // FIXME: Handle more intrinsics.
2481 switch (I.getIntrinsicID()) {
2482 default: return false;
2483 case Intrinsic::frameaddress: {
2484 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
2485 MFI->setFrameAddressIsTaken(true);
2487 unsigned LdrOpc = isThumb2 ? ARM::t2LDRi12 : ARM::LDRi12;
2488 const TargetRegisterClass *RC = isThumb2 ? &ARM::tGPRRegClass
2489 : &ARM::GPRRegClass;
2491 const ARMBaseRegisterInfo *RegInfo =
2492 static_cast<const ARMBaseRegisterInfo *>(Subtarget->getRegisterInfo());
2493 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
2494 unsigned SrcReg = FramePtr;
2496 // Recursively load frame address
2502 unsigned Depth = cast<ConstantInt>(I.getOperand(0))->getZExtValue();
2504 DestReg = createResultReg(RC);
2505 AddOptionalDefs(BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2506 TII.get(LdrOpc), DestReg)
2507 .addReg(SrcReg).addImm(0));
2510 updateValueMap(&I, SrcReg);
2513 case Intrinsic::memcpy:
2514 case Intrinsic::memmove: {
2515 const MemTransferInst &MTI = cast<MemTransferInst>(I);
2516 // Don't handle volatile.
2517 if (MTI.isVolatile())
2520 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
2521 // we would emit dead code because we don't currently handle memmoves.
2522 bool isMemCpy = (I.getIntrinsicID() == Intrinsic::memcpy);
2523 if (isa<ConstantInt>(MTI.getLength()) && isMemCpy) {
2524 // Small memcpy's are common enough that we want to do them without a call
2526 uint64_t Len = cast<ConstantInt>(MTI.getLength())->getZExtValue();
2527 if (ARMIsMemCpySmall(Len)) {
2529 if (!ARMComputeAddress(MTI.getRawDest(), Dest) ||
2530 !ARMComputeAddress(MTI.getRawSource(), Src))
2532 unsigned Alignment = MTI.getAlignment();
2533 if (ARMTryEmitSmallMemCpy(Dest, Src, Len, Alignment))
2538 if (!MTI.getLength()->getType()->isIntegerTy(32))
2541 if (MTI.getSourceAddressSpace() > 255 || MTI.getDestAddressSpace() > 255)
2544 const char *IntrMemName = isa<MemCpyInst>(I) ? "memcpy" : "memmove";
2545 return SelectCall(&I, IntrMemName);
2547 case Intrinsic::memset: {
2548 const MemSetInst &MSI = cast<MemSetInst>(I);
2549 // Don't handle volatile.
2550 if (MSI.isVolatile())
2553 if (!MSI.getLength()->getType()->isIntegerTy(32))
2556 if (MSI.getDestAddressSpace() > 255)
2559 return SelectCall(&I, "memset");
2561 case Intrinsic::trap: {
2562 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(
2563 Subtarget->useNaClTrap() ? ARM::TRAPNaCl : ARM::TRAP));
2569 bool ARMFastISel::SelectTrunc(const Instruction *I) {
2570 // The high bits for a type smaller than the register size are assumed to be
2572 Value *Op = I->getOperand(0);
2575 SrcVT = TLI.getValueType(DL, Op->getType(), true);
2576 DestVT = TLI.getValueType(DL, I->getType(), true);
2578 if (SrcVT != MVT::i32 && SrcVT != MVT::i16 && SrcVT != MVT::i8)
2580 if (DestVT != MVT::i16 && DestVT != MVT::i8 && DestVT != MVT::i1)
2583 unsigned SrcReg = getRegForValue(Op);
2584 if (!SrcReg) return false;
2586 // Because the high bits are undefined, a truncate doesn't generate
2588 updateValueMap(I, SrcReg);
2592 unsigned ARMFastISel::ARMEmitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
2594 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8)
2596 if (SrcVT != MVT::i16 && SrcVT != MVT::i8 && SrcVT != MVT::i1)
2599 // Table of which combinations can be emitted as a single instruction,
2600 // and which will require two.
2601 static const uint8_t isSingleInstrTbl[3][2][2][2] = {
2603 // !hasV6Ops hasV6Ops !hasV6Ops hasV6Ops
2604 // ext: s z s z s z s z
2605 /* 1 */ { { { 0, 1 }, { 0, 1 } }, { { 0, 0 }, { 0, 1 } } },
2606 /* 8 */ { { { 0, 1 }, { 1, 1 } }, { { 0, 0 }, { 1, 1 } } },
2607 /* 16 */ { { { 0, 0 }, { 1, 1 } }, { { 0, 0 }, { 1, 1 } } }
2610 // Target registers for:
2611 // - For ARM can never be PC.
2612 // - For 16-bit Thumb are restricted to lower 8 registers.
2613 // - For 32-bit Thumb are restricted to non-SP and non-PC.
2614 static const TargetRegisterClass *RCTbl[2][2] = {
2615 // Instructions: Two Single
2616 /* ARM */ { &ARM::GPRnopcRegClass, &ARM::GPRnopcRegClass },
2617 /* Thumb */ { &ARM::tGPRRegClass, &ARM::rGPRRegClass }
2620 // Table governing the instruction(s) to be emitted.
2621 static const struct InstructionTable {
2623 uint32_t hasS : 1; // Some instructions have an S bit, always set it to 0.
2624 uint32_t Shift : 7; // For shift operand addressing mode, used by MOVsi.
2625 uint32_t Imm : 8; // All instructions have either a shift or a mask.
2626 } IT[2][2][3][2] = {
2627 { // Two instructions (first is left shift, second is in this table).
2628 { // ARM Opc S Shift Imm
2629 /* 1 bit sext */ { { ARM::MOVsi , 1, ARM_AM::asr , 31 },
2630 /* 1 bit zext */ { ARM::MOVsi , 1, ARM_AM::lsr , 31 } },
2631 /* 8 bit sext */ { { ARM::MOVsi , 1, ARM_AM::asr , 24 },
2632 /* 8 bit zext */ { ARM::MOVsi , 1, ARM_AM::lsr , 24 } },
2633 /* 16 bit sext */ { { ARM::MOVsi , 1, ARM_AM::asr , 16 },
2634 /* 16 bit zext */ { ARM::MOVsi , 1, ARM_AM::lsr , 16 } }
2636 { // Thumb Opc S Shift Imm
2637 /* 1 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift, 31 },
2638 /* 1 bit zext */ { ARM::tLSRri , 0, ARM_AM::no_shift, 31 } },
2639 /* 8 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift, 24 },
2640 /* 8 bit zext */ { ARM::tLSRri , 0, ARM_AM::no_shift, 24 } },
2641 /* 16 bit sext */ { { ARM::tASRri , 0, ARM_AM::no_shift, 16 },
2642 /* 16 bit zext */ { ARM::tLSRri , 0, ARM_AM::no_shift, 16 } }
2645 { // Single instruction.
2646 { // ARM Opc S Shift Imm
2647 /* 1 bit sext */ { { ARM::KILL , 0, ARM_AM::no_shift, 0 },
2648 /* 1 bit zext */ { ARM::ANDri , 1, ARM_AM::no_shift, 1 } },
2649 /* 8 bit sext */ { { ARM::SXTB , 0, ARM_AM::no_shift, 0 },
2650 /* 8 bit zext */ { ARM::ANDri , 1, ARM_AM::no_shift, 255 } },
2651 /* 16 bit sext */ { { ARM::SXTH , 0, ARM_AM::no_shift, 0 },
2652 /* 16 bit zext */ { ARM::UXTH , 0, ARM_AM::no_shift, 0 } }
2654 { // Thumb Opc S Shift Imm
2655 /* 1 bit sext */ { { ARM::KILL , 0, ARM_AM::no_shift, 0 },
2656 /* 1 bit zext */ { ARM::t2ANDri, 1, ARM_AM::no_shift, 1 } },
2657 /* 8 bit sext */ { { ARM::t2SXTB , 0, ARM_AM::no_shift, 0 },
2658 /* 8 bit zext */ { ARM::t2ANDri, 1, ARM_AM::no_shift, 255 } },
2659 /* 16 bit sext */ { { ARM::t2SXTH , 0, ARM_AM::no_shift, 0 },
2660 /* 16 bit zext */ { ARM::t2UXTH , 0, ARM_AM::no_shift, 0 } }
2665 unsigned SrcBits = SrcVT.getSizeInBits();
2666 unsigned DestBits = DestVT.getSizeInBits();
2668 assert((SrcBits < DestBits) && "can only extend to larger types");
2669 assert((DestBits == 32 || DestBits == 16 || DestBits == 8) &&
2670 "other sizes unimplemented");
2671 assert((SrcBits == 16 || SrcBits == 8 || SrcBits == 1) &&
2672 "other sizes unimplemented");
2674 bool hasV6Ops = Subtarget->hasV6Ops();
2675 unsigned Bitness = SrcBits / 8; // {1,8,16}=>{0,1,2}
2676 assert((Bitness < 3) && "sanity-check table bounds");
2678 bool isSingleInstr = isSingleInstrTbl[Bitness][isThumb2][hasV6Ops][isZExt];
2679 const TargetRegisterClass *RC = RCTbl[isThumb2][isSingleInstr];
2680 const InstructionTable *ITP = &IT[isSingleInstr][isThumb2][Bitness][isZExt];
2681 unsigned Opc = ITP->Opc;
2682 assert(ARM::KILL != Opc && "Invalid table entry");
2683 unsigned hasS = ITP->hasS;
2684 ARM_AM::ShiftOpc Shift = (ARM_AM::ShiftOpc) ITP->Shift;
2685 assert(((Shift == ARM_AM::no_shift) == (Opc != ARM::MOVsi)) &&
2686 "only MOVsi has shift operand addressing mode");
2687 unsigned Imm = ITP->Imm;
2689 // 16-bit Thumb instructions always set CPSR (unless they're in an IT block).
2690 bool setsCPSR = &ARM::tGPRRegClass == RC;
2691 unsigned LSLOpc = isThumb2 ? ARM::tLSLri : ARM::MOVsi;
2693 // MOVsi encodes shift and immediate in shift operand addressing mode.
2694 // The following condition has the same value when emitting two
2695 // instruction sequences: both are shifts.
2696 bool ImmIsSO = (Shift != ARM_AM::no_shift);
2698 // Either one or two instructions are emitted.
2699 // They're always of the form:
2701 // CPSR is set only by 16-bit Thumb instructions.
2702 // Predicate, if any, is AL.
2703 // S bit, if available, is always 0.
2704 // When two are emitted the first's result will feed as the second's input,
2705 // that value is then dead.
2706 unsigned NumInstrsEmitted = isSingleInstr ? 1 : 2;
2707 for (unsigned Instr = 0; Instr != NumInstrsEmitted; ++Instr) {
2708 ResultReg = createResultReg(RC);
2709 bool isLsl = (0 == Instr) && !isSingleInstr;
2710 unsigned Opcode = isLsl ? LSLOpc : Opc;
2711 ARM_AM::ShiftOpc ShiftAM = isLsl ? ARM_AM::lsl : Shift;
2712 unsigned ImmEnc = ImmIsSO ? ARM_AM::getSORegOpc(ShiftAM, Imm) : Imm;
2713 bool isKill = 1 == Instr;
2714 MachineInstrBuilder MIB = BuildMI(
2715 *FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opcode), ResultReg);
2717 MIB.addReg(ARM::CPSR, RegState::Define);
2718 SrcReg = constrainOperandRegClass(TII.get(Opcode), SrcReg, 1 + setsCPSR);
2719 AddDefaultPred(MIB.addReg(SrcReg, isKill * RegState::Kill).addImm(ImmEnc));
2722 // Second instruction consumes the first's result.
2729 bool ARMFastISel::SelectIntExt(const Instruction *I) {
2730 // On ARM, in general, integer casts don't involve legal types; this code
2731 // handles promotable integers.
2732 Type *DestTy = I->getType();
2733 Value *Src = I->getOperand(0);
2734 Type *SrcTy = Src->getType();
2736 bool isZExt = isa<ZExtInst>(I);
2737 unsigned SrcReg = getRegForValue(Src);
2738 if (!SrcReg) return false;
2740 EVT SrcEVT, DestEVT;
2741 SrcEVT = TLI.getValueType(DL, SrcTy, true);
2742 DestEVT = TLI.getValueType(DL, DestTy, true);
2743 if (!SrcEVT.isSimple()) return false;
2744 if (!DestEVT.isSimple()) return false;
2746 MVT SrcVT = SrcEVT.getSimpleVT();
2747 MVT DestVT = DestEVT.getSimpleVT();
2748 unsigned ResultReg = ARMEmitIntExt(SrcVT, SrcReg, DestVT, isZExt);
2749 if (ResultReg == 0) return false;
2750 updateValueMap(I, ResultReg);
2754 bool ARMFastISel::SelectShift(const Instruction *I,
2755 ARM_AM::ShiftOpc ShiftTy) {
2756 // We handle thumb2 mode by target independent selector
2757 // or SelectionDAG ISel.
2761 // Only handle i32 now.
2762 EVT DestVT = TLI.getValueType(DL, I->getType(), true);
2763 if (DestVT != MVT::i32)
2766 unsigned Opc = ARM::MOVsr;
2768 Value *Src2Value = I->getOperand(1);
2769 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Src2Value)) {
2770 ShiftImm = CI->getZExtValue();
2772 // Fall back to selection DAG isel if the shift amount
2773 // is zero or greater than the width of the value type.
2774 if (ShiftImm == 0 || ShiftImm >=32)
2780 Value *Src1Value = I->getOperand(0);
2781 unsigned Reg1 = getRegForValue(Src1Value);
2782 if (Reg1 == 0) return false;
2785 if (Opc == ARM::MOVsr) {
2786 Reg2 = getRegForValue(Src2Value);
2787 if (Reg2 == 0) return false;
2790 unsigned ResultReg = createResultReg(&ARM::GPRnopcRegClass);
2791 if(ResultReg == 0) return false;
2793 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2794 TII.get(Opc), ResultReg)
2797 if (Opc == ARM::MOVsi)
2798 MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, ShiftImm));
2799 else if (Opc == ARM::MOVsr) {
2801 MIB.addImm(ARM_AM::getSORegOpc(ShiftTy, 0));
2804 AddOptionalDefs(MIB);
2805 updateValueMap(I, ResultReg);
2809 // TODO: SoftFP support.
2810 bool ARMFastISel::fastSelectInstruction(const Instruction *I) {
2812 switch (I->getOpcode()) {
2813 case Instruction::Load:
2814 return SelectLoad(I);
2815 case Instruction::Store:
2816 return SelectStore(I);
2817 case Instruction::Br:
2818 return SelectBranch(I);
2819 case Instruction::IndirectBr:
2820 return SelectIndirectBr(I);
2821 case Instruction::ICmp:
2822 case Instruction::FCmp:
2823 return SelectCmp(I);
2824 case Instruction::FPExt:
2825 return SelectFPExt(I);
2826 case Instruction::FPTrunc:
2827 return SelectFPTrunc(I);
2828 case Instruction::SIToFP:
2829 return SelectIToFP(I, /*isSigned*/ true);
2830 case Instruction::UIToFP:
2831 return SelectIToFP(I, /*isSigned*/ false);
2832 case Instruction::FPToSI:
2833 return SelectFPToI(I, /*isSigned*/ true);
2834 case Instruction::FPToUI:
2835 return SelectFPToI(I, /*isSigned*/ false);
2836 case Instruction::Add:
2837 return SelectBinaryIntOp(I, ISD::ADD);
2838 case Instruction::Or:
2839 return SelectBinaryIntOp(I, ISD::OR);
2840 case Instruction::Sub:
2841 return SelectBinaryIntOp(I, ISD::SUB);
2842 case Instruction::FAdd:
2843 return SelectBinaryFPOp(I, ISD::FADD);
2844 case Instruction::FSub:
2845 return SelectBinaryFPOp(I, ISD::FSUB);
2846 case Instruction::FMul:
2847 return SelectBinaryFPOp(I, ISD::FMUL);
2848 case Instruction::SDiv:
2849 return SelectDiv(I, /*isSigned*/ true);
2850 case Instruction::UDiv:
2851 return SelectDiv(I, /*isSigned*/ false);
2852 case Instruction::SRem:
2853 return SelectRem(I, /*isSigned*/ true);
2854 case Instruction::URem:
2855 return SelectRem(I, /*isSigned*/ false);
2856 case Instruction::Call:
2857 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2858 return SelectIntrinsicCall(*II);
2859 return SelectCall(I);
2860 case Instruction::Select:
2861 return SelectSelect(I);
2862 case Instruction::Ret:
2863 return SelectRet(I);
2864 case Instruction::Trunc:
2865 return SelectTrunc(I);
2866 case Instruction::ZExt:
2867 case Instruction::SExt:
2868 return SelectIntExt(I);
2869 case Instruction::Shl:
2870 return SelectShift(I, ARM_AM::lsl);
2871 case Instruction::LShr:
2872 return SelectShift(I, ARM_AM::lsr);
2873 case Instruction::AShr:
2874 return SelectShift(I, ARM_AM::asr);
2881 // This table describes sign- and zero-extend instructions which can be
2882 // folded into a preceding load. All of these extends have an immediate
2883 // (sometimes a mask and sometimes a shift) that's applied after
2885 const struct FoldableLoadExtendsStruct {
2886 uint16_t Opc[2]; // ARM, Thumb.
2887 uint8_t ExpectedImm;
2889 uint8_t ExpectedVT : 7;
2890 } FoldableLoadExtends[] = {
2891 { { ARM::SXTH, ARM::t2SXTH }, 0, 0, MVT::i16 },
2892 { { ARM::UXTH, ARM::t2UXTH }, 0, 1, MVT::i16 },
2893 { { ARM::ANDri, ARM::t2ANDri }, 255, 1, MVT::i8 },
2894 { { ARM::SXTB, ARM::t2SXTB }, 0, 0, MVT::i8 },
2895 { { ARM::UXTB, ARM::t2UXTB }, 0, 1, MVT::i8 }
2899 /// \brief The specified machine instr operand is a vreg, and that
2900 /// vreg is being provided by the specified load instruction. If possible,
2901 /// try to fold the load as an operand to the instruction, returning true if
2903 bool ARMFastISel::tryToFoldLoadIntoMI(MachineInstr *MI, unsigned OpNo,
2904 const LoadInst *LI) {
2905 // Verify we have a legal type before going any further.
2907 if (!isLoadTypeLegal(LI->getType(), VT))
2910 // Combine load followed by zero- or sign-extend.
2911 // ldrb r1, [r0] ldrb r1, [r0]
2913 // mov r3, r2 mov r3, r1
2914 if (MI->getNumOperands() < 3 || !MI->getOperand(2).isImm())
2916 const uint64_t Imm = MI->getOperand(2).getImm();
2920 for (unsigned i = 0, e = array_lengthof(FoldableLoadExtends);
2922 if (FoldableLoadExtends[i].Opc[isThumb2] == MI->getOpcode() &&
2923 (uint64_t)FoldableLoadExtends[i].ExpectedImm == Imm &&
2924 MVT((MVT::SimpleValueType)FoldableLoadExtends[i].ExpectedVT) == VT) {
2926 isZExt = FoldableLoadExtends[i].isZExt;
2929 if (!Found) return false;
2931 // See if we can handle this address.
2933 if (!ARMComputeAddress(LI->getOperand(0), Addr)) return false;
2935 unsigned ResultReg = MI->getOperand(0).getReg();
2936 if (!ARMEmitLoad(VT, ResultReg, Addr, LI->getAlignment(), isZExt, false))
2938 MI->eraseFromParent();
2942 unsigned ARMFastISel::ARMLowerPICELF(const GlobalValue *GV,
2943 unsigned Align, MVT VT) {
2944 bool UseGOT_PREL = !TM.shouldAssumeDSOLocal(*GV->getParent(), GV);
2946 LLVMContext *Context = &MF->getFunction()->getContext();
2947 unsigned ARMPCLabelIndex = AFI->createPICLabelUId();
2948 unsigned PCAdj = Subtarget->isThumb() ? 4 : 8;
2949 ARMConstantPoolValue *CPV = ARMConstantPoolConstant::Create(
2950 GV, ARMPCLabelIndex, ARMCP::CPValue, PCAdj,
2951 UseGOT_PREL ? ARMCP::GOT_PREL : ARMCP::no_modifier,
2952 /*AddCurrentAddress=*/UseGOT_PREL);
2954 unsigned ConstAlign =
2955 MF->getDataLayout().getPrefTypeAlignment(Type::getInt32PtrTy(*Context));
2956 unsigned Idx = MF->getConstantPool()->getConstantPoolIndex(CPV, ConstAlign);
2958 unsigned TempReg = MF->getRegInfo().createVirtualRegister(&ARM::rGPRRegClass);
2959 unsigned Opc = isThumb2 ? ARM::t2LDRpci : ARM::LDRcp;
2960 MachineInstrBuilder MIB =
2961 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), TempReg)
2962 .addConstantPoolIndex(Idx);
2963 if (Opc == ARM::LDRcp)
2965 AddDefaultPred(MIB);
2967 // Fix the address by adding pc.
2968 unsigned DestReg = createResultReg(TLI.getRegClassFor(VT));
2969 Opc = Subtarget->isThumb() ? ARM::tPICADD : UseGOT_PREL ? ARM::PICLDR
2971 DestReg = constrainOperandRegClass(TII.get(Opc), DestReg, 0);
2972 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), DestReg)
2974 .addImm(ARMPCLabelIndex);
2975 if (!Subtarget->isThumb())
2976 AddDefaultPred(MIB);
2978 if (UseGOT_PREL && Subtarget->isThumb()) {
2979 unsigned NewDestReg = createResultReg(TLI.getRegClassFor(VT));
2980 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2981 TII.get(ARM::t2LDRi12), NewDestReg)
2984 DestReg = NewDestReg;
2985 AddOptionalDefs(MIB);
2990 bool ARMFastISel::fastLowerArguments() {
2991 if (!FuncInfo.CanLowerReturn)
2994 const Function *F = FuncInfo.Fn;
2998 CallingConv::ID CC = F->getCallingConv();
3002 case CallingConv::Fast:
3003 case CallingConv::C:
3004 case CallingConv::ARM_AAPCS_VFP:
3005 case CallingConv::ARM_AAPCS:
3006 case CallingConv::ARM_APCS:
3007 case CallingConv::Swift:
3011 // Only handle simple cases. i.e. Up to 4 i8/i16/i32 scalar arguments
3012 // which are passed in r0 - r3.
3014 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
3015 I != E; ++I, ++Idx) {
3019 if (F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
3020 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
3021 F->getAttributes().hasAttribute(Idx, Attribute::SwiftSelf) ||
3022 F->getAttributes().hasAttribute(Idx, Attribute::SwiftError) ||
3023 F->getAttributes().hasAttribute(Idx, Attribute::ByVal))
3026 Type *ArgTy = I->getType();
3027 if (ArgTy->isStructTy() || ArgTy->isArrayTy() || ArgTy->isVectorTy())
3030 EVT ArgVT = TLI.getValueType(DL, ArgTy);
3031 if (!ArgVT.isSimple()) return false;
3032 switch (ArgVT.getSimpleVT().SimpleTy) {
3043 static const MCPhysReg GPRArgRegs[] = {
3044 ARM::R0, ARM::R1, ARM::R2, ARM::R3
3047 const TargetRegisterClass *RC = &ARM::rGPRRegClass;
3049 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
3050 I != E; ++I, ++Idx) {
3051 unsigned SrcReg = GPRArgRegs[Idx];
3052 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
3053 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
3054 // Without this, EmitLiveInCopies may eliminate the livein if its only
3055 // use is a bitcast (which isn't turned into an instruction).
3056 unsigned ResultReg = createResultReg(RC);
3057 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3058 TII.get(TargetOpcode::COPY),
3059 ResultReg).addReg(DstReg, getKillRegState(true));
3060 updateValueMap(&*I, ResultReg);
3067 FastISel *ARM::createFastISel(FunctionLoweringInfo &funcInfo,
3068 const TargetLibraryInfo *libInfo) {
3069 if (funcInfo.MF->getSubtarget<ARMSubtarget>().useFastISel())
3070 return new ARMFastISel(funcInfo, libInfo);