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