1 //===-- AArch6464FastISel.cpp - AArch64 FastISel implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the AArch64-specific support for the FastISel class. Some
11 // of the target-specific code is generated by tablegen in the file
12 // AArch64GenFastISel.inc, which is #included here.
14 //===----------------------------------------------------------------------===//
17 #include "AArch64Subtarget.h"
18 #include "AArch64TargetMachine.h"
19 #include "MCTargetDesc/AArch64AddressingModes.h"
20 #include "llvm/Analysis/BranchProbabilityInfo.h"
21 #include "llvm/CodeGen/CallingConvLower.h"
22 #include "llvm/CodeGen/FastISel.h"
23 #include "llvm/CodeGen/FunctionLoweringInfo.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/IR/CallingConv.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/DerivedTypes.h"
31 #include "llvm/IR/Function.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Instructions.h"
36 #include "llvm/IR/IntrinsicInst.h"
37 #include "llvm/IR/Operator.h"
38 #include "llvm/Support/CommandLine.h"
43 class AArch64FastISel final : public FastISel {
53 AArch64_AM::ShiftExtendType ExtType;
61 const GlobalValue *GV;
64 Address() : Kind(RegBase), ExtType(AArch64_AM::InvalidShiftExtend),
65 OffsetReg(0), Shift(0), Offset(0), GV(nullptr) { Base.Reg = 0; }
66 void setKind(BaseKind K) { Kind = K; }
67 BaseKind getKind() const { return Kind; }
68 void setExtendType(AArch64_AM::ShiftExtendType E) { ExtType = E; }
69 AArch64_AM::ShiftExtendType getExtendType() const { return ExtType; }
70 bool isRegBase() const { return Kind == RegBase; }
71 bool isFIBase() const { return Kind == FrameIndexBase; }
72 void setReg(unsigned Reg) {
73 assert(isRegBase() && "Invalid base register access!");
76 unsigned getReg() const {
77 assert(isRegBase() && "Invalid base register access!");
80 void setOffsetReg(unsigned Reg) {
81 assert(isRegBase() && "Invalid offset register access!");
84 unsigned getOffsetReg() const {
85 assert(isRegBase() && "Invalid offset register access!");
88 void setFI(unsigned FI) {
89 assert(isFIBase() && "Invalid base frame index access!");
92 unsigned getFI() const {
93 assert(isFIBase() && "Invalid base frame index access!");
96 void setOffset(int64_t O) { Offset = O; }
97 int64_t getOffset() { return Offset; }
98 void setShift(unsigned S) { Shift = S; }
99 unsigned getShift() { return Shift; }
101 void setGlobalValue(const GlobalValue *G) { GV = G; }
102 const GlobalValue *getGlobalValue() { return GV; }
105 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
106 /// make the right decision when generating code for different targets.
107 const AArch64Subtarget *Subtarget;
108 LLVMContext *Context;
110 bool fastLowerArguments() override;
111 bool fastLowerCall(CallLoweringInfo &CLI) override;
112 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
115 // Selection routines.
116 bool selectAddSub(const Instruction *I);
117 bool selectLogicalOp(const Instruction *I);
118 bool selectLoad(const Instruction *I);
119 bool selectStore(const Instruction *I);
120 bool selectBranch(const Instruction *I);
121 bool selectIndirectBr(const Instruction *I);
122 bool selectCmp(const Instruction *I);
123 bool selectSelect(const Instruction *I);
124 bool selectFPExt(const Instruction *I);
125 bool selectFPTrunc(const Instruction *I);
126 bool selectFPToInt(const Instruction *I, bool Signed);
127 bool selectIntToFP(const Instruction *I, bool Signed);
128 bool selectRem(const Instruction *I, unsigned ISDOpcode);
129 bool selectRet(const Instruction *I);
130 bool selectTrunc(const Instruction *I);
131 bool selectIntExt(const Instruction *I);
132 bool selectMul(const Instruction *I);
133 bool selectShift(const Instruction *I);
134 bool selectBitCast(const Instruction *I);
135 bool selectFRem(const Instruction *I);
136 bool selectSDiv(const Instruction *I);
137 bool selectGetElementPtr(const Instruction *I);
139 // Utility helper routines.
140 bool isTypeLegal(Type *Ty, MVT &VT);
141 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
142 bool isValueAvailable(const Value *V) const;
143 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
144 bool computeCallAddress(const Value *V, Address &Addr);
145 bool simplifyAddress(Address &Addr, MVT VT);
146 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
147 unsigned Flags, unsigned ScaleFactor,
148 MachineMemOperand *MMO);
149 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
150 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
152 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
154 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
156 // Emit helper routines.
157 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
158 const Value *RHS, bool SetFlags = false,
159 bool WantResult = true, bool IsZExt = false);
160 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
161 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
162 bool SetFlags = false, bool WantResult = true);
163 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
164 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
165 bool WantResult = true);
166 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
167 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
168 AArch64_AM::ShiftExtendType ShiftType,
169 uint64_t ShiftImm, bool SetFlags = false,
170 bool WantResult = true);
171 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
172 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
173 AArch64_AM::ShiftExtendType ExtType,
174 uint64_t ShiftImm, bool SetFlags = false,
175 bool WantResult = true);
178 bool emitCompareAndBranch(const BranchInst *BI);
179 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
180 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
181 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
182 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
183 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
184 MachineMemOperand *MMO = nullptr);
185 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
186 MachineMemOperand *MMO = nullptr);
187 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
188 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
189 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
190 bool SetFlags = false, bool WantResult = true,
191 bool IsZExt = false);
192 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
193 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
194 bool SetFlags = false, bool WantResult = true,
195 bool IsZExt = false);
196 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
197 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
198 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
199 unsigned RHSReg, bool RHSIsKill,
200 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
201 bool WantResult = true);
202 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
204 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
205 bool LHSIsKill, uint64_t Imm);
206 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
207 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
209 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
210 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
211 unsigned Op1, bool Op1IsKill);
212 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
213 unsigned Op1, bool Op1IsKill);
214 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
215 unsigned Op1, bool Op1IsKill);
216 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
217 unsigned Op1Reg, bool Op1IsKill);
218 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
219 uint64_t Imm, bool IsZExt = true);
220 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
221 unsigned Op1Reg, bool Op1IsKill);
222 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
223 uint64_t Imm, bool IsZExt = true);
224 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
225 unsigned Op1Reg, bool Op1IsKill);
226 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
227 uint64_t Imm, bool IsZExt = false);
229 unsigned materializeInt(const ConstantInt *CI, MVT VT);
230 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
231 unsigned materializeGV(const GlobalValue *GV);
233 // Call handling routines.
235 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
236 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
238 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
241 // Backend specific FastISel code.
242 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
243 unsigned fastMaterializeConstant(const Constant *C) override;
244 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
246 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
247 const TargetLibraryInfo *LibInfo)
248 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
249 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
250 Context = &FuncInfo.Fn->getContext();
253 bool fastSelectInstruction(const Instruction *I) override;
255 #include "AArch64GenFastISel.inc"
258 } // end anonymous namespace
260 #include "AArch64GenCallingConv.inc"
262 /// \brief Check if the sign-/zero-extend will be a noop.
263 static bool isIntExtFree(const Instruction *I) {
264 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
265 "Unexpected integer extend instruction.");
266 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
267 "Unexpected value type.");
268 bool IsZExt = isa<ZExtInst>(I);
270 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
274 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
275 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
281 /// \brief Determine the implicit scale factor that is applied by a memory
282 /// operation for a given value type.
283 static unsigned getImplicitScaleFactor(MVT VT) {
284 switch (VT.SimpleTy) {
287 case MVT::i1: // fall-through
292 case MVT::i32: // fall-through
295 case MVT::i64: // fall-through
301 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
302 if (CC == CallingConv::WebKit_JS)
303 return CC_AArch64_WebKit_JS;
304 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
307 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
308 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
309 "Alloca should always return a pointer.");
311 // Don't handle dynamic allocas.
312 if (!FuncInfo.StaticAllocaMap.count(AI))
315 DenseMap<const AllocaInst *, int>::iterator SI =
316 FuncInfo.StaticAllocaMap.find(AI);
318 if (SI != FuncInfo.StaticAllocaMap.end()) {
319 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
320 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
322 .addFrameIndex(SI->second)
331 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
336 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
338 // Create a copy from the zero register to materialize a "0" value.
339 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
340 : &AArch64::GPR32RegClass;
341 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
342 unsigned ResultReg = createResultReg(RC);
343 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
344 ResultReg).addReg(ZeroReg, getKillRegState(true));
348 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
349 // Positive zero (+0.0) has to be materialized with a fmov from the zero
350 // register, because the immediate version of fmov cannot encode zero.
351 if (CFP->isNullValue())
352 return fastMaterializeFloatZero(CFP);
354 if (VT != MVT::f32 && VT != MVT::f64)
357 const APFloat Val = CFP->getValueAPF();
358 bool Is64Bit = (VT == MVT::f64);
359 // This checks to see if we can use FMOV instructions to materialize
360 // a constant, otherwise we have to materialize via the constant pool.
361 if (TLI.isFPImmLegal(Val, VT)) {
363 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
364 assert((Imm != -1) && "Cannot encode floating-point constant.");
365 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
366 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
369 // Materialize via constant pool. MachineConstantPool wants an explicit
371 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
373 Align = DL.getTypeAllocSize(CFP->getType());
375 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
376 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
377 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
378 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
380 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
381 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
382 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
384 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
388 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
389 // We can't handle thread-local variables quickly yet.
390 if (GV->isThreadLocal())
393 // MachO still uses GOT for large code-model accesses, but ELF requires
394 // movz/movk sequences, which FastISel doesn't handle yet.
395 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
398 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
400 EVT DestEVT = TLI.getValueType(GV->getType(), true);
401 if (!DestEVT.isSimple())
404 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
407 if (OpFlags & AArch64II::MO_GOT) {
409 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
411 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
413 ResultReg = createResultReg(&AArch64::GPR64RegClass);
414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
417 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
419 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
420 // We can't handle addresses loaded from a constant pool quickly yet.
424 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
426 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
428 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
429 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
432 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
438 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
439 EVT CEVT = TLI.getValueType(C->getType(), true);
441 // Only handle simple types.
442 if (!CEVT.isSimple())
444 MVT VT = CEVT.getSimpleVT();
446 if (const auto *CI = dyn_cast<ConstantInt>(C))
447 return materializeInt(CI, VT);
448 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
449 return materializeFP(CFP, VT);
450 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
451 return materializeGV(GV);
456 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
457 assert(CFP->isNullValue() &&
458 "Floating-point constant is not a positive zero.");
460 if (!isTypeLegal(CFP->getType(), VT))
463 if (VT != MVT::f32 && VT != MVT::f64)
466 bool Is64Bit = (VT == MVT::f64);
467 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
468 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
469 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
472 /// \brief Check if the multiply is by a power-of-2 constant.
473 static bool isMulPowOf2(const Value *I) {
474 if (const auto *MI = dyn_cast<MulOperator>(I)) {
475 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
476 if (C->getValue().isPowerOf2())
478 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
479 if (C->getValue().isPowerOf2())
485 // Computes the address to get to an object.
486 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
488 const User *U = nullptr;
489 unsigned Opcode = Instruction::UserOp1;
490 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
491 // Don't walk into other basic blocks unless the object is an alloca from
492 // another block, otherwise it may not have a virtual register assigned.
493 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
494 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
495 Opcode = I->getOpcode();
498 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
499 Opcode = C->getOpcode();
503 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
504 if (Ty->getAddressSpace() > 255)
505 // Fast instruction selection doesn't support the special
512 case Instruction::BitCast: {
513 // Look through bitcasts.
514 return computeAddress(U->getOperand(0), Addr, Ty);
516 case Instruction::IntToPtr: {
517 // Look past no-op inttoptrs.
518 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
519 return computeAddress(U->getOperand(0), Addr, Ty);
522 case Instruction::PtrToInt: {
523 // Look past no-op ptrtoints.
524 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
525 return computeAddress(U->getOperand(0), Addr, Ty);
528 case Instruction::GetElementPtr: {
529 Address SavedAddr = Addr;
530 uint64_t TmpOffset = Addr.getOffset();
532 // Iterate through the GEP folding the constants into offsets where
534 gep_type_iterator GTI = gep_type_begin(U);
535 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
537 const Value *Op = *i;
538 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
539 const StructLayout *SL = DL.getStructLayout(STy);
540 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
541 TmpOffset += SL->getElementOffset(Idx);
543 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
545 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
546 // Constant-offset addressing.
547 TmpOffset += CI->getSExtValue() * S;
550 if (canFoldAddIntoGEP(U, Op)) {
551 // A compatible add with a constant operand. Fold the constant.
553 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
554 TmpOffset += CI->getSExtValue() * S;
555 // Iterate on the other operand.
556 Op = cast<AddOperator>(Op)->getOperand(0);
560 goto unsupported_gep;
565 // Try to grab the base operand now.
566 Addr.setOffset(TmpOffset);
567 if (computeAddress(U->getOperand(0), Addr, Ty))
570 // We failed, restore everything and try the other options.
576 case Instruction::Alloca: {
577 const AllocaInst *AI = cast<AllocaInst>(Obj);
578 DenseMap<const AllocaInst *, int>::iterator SI =
579 FuncInfo.StaticAllocaMap.find(AI);
580 if (SI != FuncInfo.StaticAllocaMap.end()) {
581 Addr.setKind(Address::FrameIndexBase);
582 Addr.setFI(SI->second);
587 case Instruction::Add: {
588 // Adds of constants are common and easy enough.
589 const Value *LHS = U->getOperand(0);
590 const Value *RHS = U->getOperand(1);
592 if (isa<ConstantInt>(LHS))
595 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
596 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
597 return computeAddress(LHS, Addr, Ty);
600 Address Backup = Addr;
601 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
607 case Instruction::Sub: {
608 // Subs of constants are common and easy enough.
609 const Value *LHS = U->getOperand(0);
610 const Value *RHS = U->getOperand(1);
612 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
613 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
614 return computeAddress(LHS, Addr, Ty);
618 case Instruction::Shl: {
619 if (Addr.getOffsetReg())
622 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
626 unsigned Val = CI->getZExtValue();
627 if (Val < 1 || Val > 3)
630 uint64_t NumBytes = 0;
631 if (Ty && Ty->isSized()) {
632 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
633 NumBytes = NumBits / 8;
634 if (!isPowerOf2_64(NumBits))
638 if (NumBytes != (1ULL << Val))
642 Addr.setExtendType(AArch64_AM::LSL);
644 const Value *Src = U->getOperand(0);
645 if (const auto *I = dyn_cast<Instruction>(Src))
646 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
649 // Fold the zext or sext when it won't become a noop.
650 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
651 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
652 Addr.setExtendType(AArch64_AM::UXTW);
653 Src = ZE->getOperand(0);
655 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
656 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
657 Addr.setExtendType(AArch64_AM::SXTW);
658 Src = SE->getOperand(0);
662 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
663 if (AI->getOpcode() == Instruction::And) {
664 const Value *LHS = AI->getOperand(0);
665 const Value *RHS = AI->getOperand(1);
667 if (const auto *C = dyn_cast<ConstantInt>(LHS))
668 if (C->getValue() == 0xffffffff)
671 if (const auto *C = dyn_cast<ConstantInt>(RHS))
672 if (C->getValue() == 0xffffffff) {
673 Addr.setExtendType(AArch64_AM::UXTW);
674 unsigned Reg = getRegForValue(LHS);
677 bool RegIsKill = hasTrivialKill(LHS);
678 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
680 Addr.setOffsetReg(Reg);
685 unsigned Reg = getRegForValue(Src);
688 Addr.setOffsetReg(Reg);
691 case Instruction::Mul: {
692 if (Addr.getOffsetReg())
698 const Value *LHS = U->getOperand(0);
699 const Value *RHS = U->getOperand(1);
701 // Canonicalize power-of-2 value to the RHS.
702 if (const auto *C = dyn_cast<ConstantInt>(LHS))
703 if (C->getValue().isPowerOf2())
706 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
707 const auto *C = cast<ConstantInt>(RHS);
708 unsigned Val = C->getValue().logBase2();
709 if (Val < 1 || Val > 3)
712 uint64_t NumBytes = 0;
713 if (Ty && Ty->isSized()) {
714 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
715 NumBytes = NumBits / 8;
716 if (!isPowerOf2_64(NumBits))
720 if (NumBytes != (1ULL << Val))
724 Addr.setExtendType(AArch64_AM::LSL);
726 const Value *Src = LHS;
727 if (const auto *I = dyn_cast<Instruction>(Src))
728 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
732 // Fold the zext or sext when it won't become a noop.
733 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
734 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
735 Addr.setExtendType(AArch64_AM::UXTW);
736 Src = ZE->getOperand(0);
738 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
739 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
740 Addr.setExtendType(AArch64_AM::SXTW);
741 Src = SE->getOperand(0);
745 unsigned Reg = getRegForValue(Src);
748 Addr.setOffsetReg(Reg);
751 case Instruction::And: {
752 if (Addr.getOffsetReg())
755 if (DL.getTypeSizeInBits(Ty) != 8)
758 const Value *LHS = U->getOperand(0);
759 const Value *RHS = U->getOperand(1);
761 if (const auto *C = dyn_cast<ConstantInt>(LHS))
762 if (C->getValue() == 0xffffffff)
765 if (const auto *C = dyn_cast<ConstantInt>(RHS))
766 if (C->getValue() == 0xffffffff) {
768 Addr.setExtendType(AArch64_AM::LSL);
769 Addr.setExtendType(AArch64_AM::UXTW);
771 unsigned Reg = getRegForValue(LHS);
774 bool RegIsKill = hasTrivialKill(LHS);
775 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
777 Addr.setOffsetReg(Reg);
782 case Instruction::SExt:
783 case Instruction::ZExt: {
784 if (!Addr.getReg() || Addr.getOffsetReg())
787 const Value *Src = nullptr;
788 // Fold the zext or sext when it won't become a noop.
789 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
790 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
791 Addr.setExtendType(AArch64_AM::UXTW);
792 Src = ZE->getOperand(0);
794 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
795 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
796 Addr.setExtendType(AArch64_AM::SXTW);
797 Src = SE->getOperand(0);
805 unsigned Reg = getRegForValue(Src);
808 Addr.setOffsetReg(Reg);
814 if (!Addr.getOffsetReg()) {
815 unsigned Reg = getRegForValue(Obj);
818 Addr.setOffsetReg(Reg);
824 unsigned Reg = getRegForValue(Obj);
831 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
832 const User *U = nullptr;
833 unsigned Opcode = Instruction::UserOp1;
836 if (const auto *I = dyn_cast<Instruction>(V)) {
837 Opcode = I->getOpcode();
839 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
840 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
841 Opcode = C->getOpcode();
847 case Instruction::BitCast:
848 // Look past bitcasts if its operand is in the same BB.
850 return computeCallAddress(U->getOperand(0), Addr);
852 case Instruction::IntToPtr:
853 // Look past no-op inttoptrs if its operand is in the same BB.
855 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
856 return computeCallAddress(U->getOperand(0), Addr);
858 case Instruction::PtrToInt:
859 // Look past no-op ptrtoints if its operand is in the same BB.
861 TLI.getValueType(U->getType()) == TLI.getPointerTy())
862 return computeCallAddress(U->getOperand(0), Addr);
866 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
867 Addr.setGlobalValue(GV);
871 // If all else fails, try to materialize the value in a register.
872 if (!Addr.getGlobalValue()) {
873 Addr.setReg(getRegForValue(V));
874 return Addr.getReg() != 0;
881 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
882 EVT evt = TLI.getValueType(Ty, true);
884 // Only handle simple types.
885 if (evt == MVT::Other || !evt.isSimple())
887 VT = evt.getSimpleVT();
889 // This is a legal type, but it's not something we handle in fast-isel.
893 // Handle all other legal types, i.e. a register that will directly hold this
895 return TLI.isTypeLegal(VT);
898 /// \brief Determine if the value type is supported by FastISel.
900 /// FastISel for AArch64 can handle more value types than are legal. This adds
901 /// simple value type such as i1, i8, and i16.
902 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
903 if (Ty->isVectorTy() && !IsVectorAllowed)
906 if (isTypeLegal(Ty, VT))
909 // If this is a type than can be sign or zero-extended to a basic operation
910 // go ahead and accept it now.
911 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
917 bool AArch64FastISel::isValueAvailable(const Value *V) const {
918 if (!isa<Instruction>(V))
921 const auto *I = cast<Instruction>(V);
922 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
928 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
929 unsigned ScaleFactor = getImplicitScaleFactor(VT);
933 bool ImmediateOffsetNeedsLowering = false;
934 bool RegisterOffsetNeedsLowering = false;
935 int64_t Offset = Addr.getOffset();
936 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
937 ImmediateOffsetNeedsLowering = true;
938 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
939 !isUInt<12>(Offset / ScaleFactor))
940 ImmediateOffsetNeedsLowering = true;
942 // Cannot encode an offset register and an immediate offset in the same
943 // instruction. Fold the immediate offset into the load/store instruction and
944 // emit an additonal add to take care of the offset register.
945 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.isRegBase() &&
947 RegisterOffsetNeedsLowering = true;
949 // Cannot encode zero register as base.
950 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
951 RegisterOffsetNeedsLowering = true;
953 // If this is a stack pointer and the offset needs to be simplified then put
954 // the alloca address into a register, set the base type back to register and
955 // continue. This should almost never happen.
956 if (ImmediateOffsetNeedsLowering && Addr.isFIBase()) {
957 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
958 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
960 .addFrameIndex(Addr.getFI())
963 Addr.setKind(Address::RegBase);
964 Addr.setReg(ResultReg);
967 if (RegisterOffsetNeedsLowering) {
968 unsigned ResultReg = 0;
970 if (Addr.getExtendType() == AArch64_AM::SXTW ||
971 Addr.getExtendType() == AArch64_AM::UXTW )
972 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
973 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
974 /*TODO:IsKill=*/false, Addr.getExtendType(),
977 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
978 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
979 /*TODO:IsKill=*/false, AArch64_AM::LSL,
982 if (Addr.getExtendType() == AArch64_AM::UXTW)
983 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
984 /*Op0IsKill=*/false, Addr.getShift(),
986 else if (Addr.getExtendType() == AArch64_AM::SXTW)
987 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
988 /*Op0IsKill=*/false, Addr.getShift(),
991 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
992 /*Op0IsKill=*/false, Addr.getShift());
997 Addr.setReg(ResultReg);
998 Addr.setOffsetReg(0);
1000 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1003 // Since the offset is too large for the load/store instruction get the
1004 // reg+offset into a register.
1005 if (ImmediateOffsetNeedsLowering) {
1008 // Try to fold the immediate into the add instruction.
1009 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1011 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1015 Addr.setReg(ResultReg);
1021 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1022 const MachineInstrBuilder &MIB,
1024 unsigned ScaleFactor,
1025 MachineMemOperand *MMO) {
1026 int64_t Offset = Addr.getOffset() / ScaleFactor;
1027 // Frame base works a bit differently. Handle it separately.
1028 if (Addr.isFIBase()) {
1029 int FI = Addr.getFI();
1030 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1031 // and alignment should be based on the VT.
1032 MMO = FuncInfo.MF->getMachineMemOperand(
1033 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1034 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1035 // Now add the rest of the operands.
1036 MIB.addFrameIndex(FI).addImm(Offset);
1038 assert(Addr.isRegBase() && "Unexpected address kind.");
1039 const MCInstrDesc &II = MIB->getDesc();
1040 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1042 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1044 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1045 if (Addr.getOffsetReg()) {
1046 assert(Addr.getOffset() == 0 && "Unexpected offset");
1047 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1048 Addr.getExtendType() == AArch64_AM::SXTX;
1049 MIB.addReg(Addr.getReg());
1050 MIB.addReg(Addr.getOffsetReg());
1051 MIB.addImm(IsSigned);
1052 MIB.addImm(Addr.getShift() != 0);
1054 MIB.addReg(Addr.getReg());
1060 MIB.addMemOperand(MMO);
1063 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1064 const Value *RHS, bool SetFlags,
1065 bool WantResult, bool IsZExt) {
1066 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1067 bool NeedExtend = false;
1068 switch (RetVT.SimpleTy) {
1076 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1080 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1082 case MVT::i32: // fall-through
1087 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1089 // Canonicalize immediates to the RHS first.
1090 if (UseAdd && isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1091 std::swap(LHS, RHS);
1093 // Canonicalize mul by power of 2 to the RHS.
1094 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1095 if (isMulPowOf2(LHS))
1096 std::swap(LHS, RHS);
1098 // Canonicalize shift immediate to the RHS.
1099 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1100 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1101 if (isa<ConstantInt>(SI->getOperand(1)))
1102 if (SI->getOpcode() == Instruction::Shl ||
1103 SI->getOpcode() == Instruction::LShr ||
1104 SI->getOpcode() == Instruction::AShr )
1105 std::swap(LHS, RHS);
1107 unsigned LHSReg = getRegForValue(LHS);
1110 bool LHSIsKill = hasTrivialKill(LHS);
1113 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1115 unsigned ResultReg = 0;
1116 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1117 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1118 if (C->isNegative())
1119 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1120 SetFlags, WantResult);
1122 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1128 // Only extend the RHS within the instruction if there is a valid extend type.
1129 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1130 isValueAvailable(RHS)) {
1131 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1132 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1133 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1134 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1137 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1138 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1139 RHSIsKill, ExtendType, C->getZExtValue(),
1140 SetFlags, WantResult);
1142 unsigned RHSReg = getRegForValue(RHS);
1145 bool RHSIsKill = hasTrivialKill(RHS);
1146 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1147 ExtendType, 0, SetFlags, WantResult);
1150 // Check if the mul can be folded into the instruction.
1151 if (RHS->hasOneUse() && isValueAvailable(RHS))
1152 if (isMulPowOf2(RHS)) {
1153 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1154 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1156 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1157 if (C->getValue().isPowerOf2())
1158 std::swap(MulLHS, MulRHS);
1160 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1161 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1162 unsigned RHSReg = getRegForValue(MulLHS);
1165 bool RHSIsKill = hasTrivialKill(MulLHS);
1166 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1167 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1170 // Check if the shift can be folded into the instruction.
1171 if (RHS->hasOneUse() && isValueAvailable(RHS))
1172 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1173 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1174 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1175 switch (SI->getOpcode()) {
1177 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1178 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1179 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1181 uint64_t ShiftVal = C->getZExtValue();
1182 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1183 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1186 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1187 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1188 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1194 unsigned RHSReg = getRegForValue(RHS);
1197 bool RHSIsKill = hasTrivialKill(RHS);
1200 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1202 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1203 SetFlags, WantResult);
1206 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1207 bool LHSIsKill, unsigned RHSReg,
1208 bool RHSIsKill, bool SetFlags,
1210 assert(LHSReg && RHSReg && "Invalid register number.");
1212 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1215 static const unsigned OpcTable[2][2][2] = {
1216 { { AArch64::SUBWrr, AArch64::SUBXrr },
1217 { AArch64::ADDWrr, AArch64::ADDXrr } },
1218 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1219 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1221 bool Is64Bit = RetVT == MVT::i64;
1222 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1223 const TargetRegisterClass *RC =
1224 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1227 ResultReg = createResultReg(RC);
1229 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1231 const MCInstrDesc &II = TII.get(Opc);
1232 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1233 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1234 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1235 .addReg(LHSReg, getKillRegState(LHSIsKill))
1236 .addReg(RHSReg, getKillRegState(RHSIsKill));
1240 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1241 bool LHSIsKill, uint64_t Imm,
1242 bool SetFlags, bool WantResult) {
1243 assert(LHSReg && "Invalid register number.");
1245 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1249 if (isUInt<12>(Imm))
1251 else if ((Imm & 0xfff000) == Imm) {
1257 static const unsigned OpcTable[2][2][2] = {
1258 { { AArch64::SUBWri, AArch64::SUBXri },
1259 { AArch64::ADDWri, AArch64::ADDXri } },
1260 { { AArch64::SUBSWri, AArch64::SUBSXri },
1261 { AArch64::ADDSWri, AArch64::ADDSXri } }
1263 bool Is64Bit = RetVT == MVT::i64;
1264 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1265 const TargetRegisterClass *RC;
1267 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1269 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1272 ResultReg = createResultReg(RC);
1274 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1276 const MCInstrDesc &II = TII.get(Opc);
1277 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1278 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1279 .addReg(LHSReg, getKillRegState(LHSIsKill))
1281 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1285 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1286 bool LHSIsKill, unsigned RHSReg,
1288 AArch64_AM::ShiftExtendType ShiftType,
1289 uint64_t ShiftImm, bool SetFlags,
1291 assert(LHSReg && RHSReg && "Invalid register number.");
1293 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1296 static const unsigned OpcTable[2][2][2] = {
1297 { { AArch64::SUBWrs, AArch64::SUBXrs },
1298 { AArch64::ADDWrs, AArch64::ADDXrs } },
1299 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1300 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1302 bool Is64Bit = RetVT == MVT::i64;
1303 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1304 const TargetRegisterClass *RC =
1305 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1308 ResultReg = createResultReg(RC);
1310 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1312 const MCInstrDesc &II = TII.get(Opc);
1313 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1314 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1315 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1316 .addReg(LHSReg, getKillRegState(LHSIsKill))
1317 .addReg(RHSReg, getKillRegState(RHSIsKill))
1318 .addImm(getShifterImm(ShiftType, ShiftImm));
1322 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1323 bool LHSIsKill, unsigned RHSReg,
1325 AArch64_AM::ShiftExtendType ExtType,
1326 uint64_t ShiftImm, bool SetFlags,
1328 assert(LHSReg && RHSReg && "Invalid register number.");
1330 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1333 static const unsigned OpcTable[2][2][2] = {
1334 { { AArch64::SUBWrx, AArch64::SUBXrx },
1335 { AArch64::ADDWrx, AArch64::ADDXrx } },
1336 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1337 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1339 bool Is64Bit = RetVT == MVT::i64;
1340 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1341 const TargetRegisterClass *RC = nullptr;
1343 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1345 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1348 ResultReg = createResultReg(RC);
1350 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1352 const MCInstrDesc &II = TII.get(Opc);
1353 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1354 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1355 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1356 .addReg(LHSReg, getKillRegState(LHSIsKill))
1357 .addReg(RHSReg, getKillRegState(RHSIsKill))
1358 .addImm(getArithExtendImm(ExtType, ShiftImm));
1362 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1363 Type *Ty = LHS->getType();
1364 EVT EVT = TLI.getValueType(Ty, true);
1365 if (!EVT.isSimple())
1367 MVT VT = EVT.getSimpleVT();
1369 switch (VT.SimpleTy) {
1377 return emitICmp(VT, LHS, RHS, IsZExt);
1380 return emitFCmp(VT, LHS, RHS);
1384 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1386 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1390 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1392 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1393 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1396 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1397 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1400 // Check to see if the 2nd operand is a constant that we can encode directly
1402 bool UseImm = false;
1403 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1404 if (CFP->isZero() && !CFP->isNegative())
1407 unsigned LHSReg = getRegForValue(LHS);
1410 bool LHSIsKill = hasTrivialKill(LHS);
1413 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1414 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1415 .addReg(LHSReg, getKillRegState(LHSIsKill));
1419 unsigned RHSReg = getRegForValue(RHS);
1422 bool RHSIsKill = hasTrivialKill(RHS);
1424 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1425 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1426 .addReg(LHSReg, getKillRegState(LHSIsKill))
1427 .addReg(RHSReg, getKillRegState(RHSIsKill));
1431 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1432 bool SetFlags, bool WantResult, bool IsZExt) {
1433 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1437 /// \brief This method is a wrapper to simplify add emission.
1439 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1440 /// that fails, then try to materialize the immediate into a register and use
1441 /// emitAddSub_rr instead.
1442 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1446 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1448 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1453 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1457 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1461 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1462 bool SetFlags, bool WantResult, bool IsZExt) {
1463 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1467 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1468 bool LHSIsKill, unsigned RHSReg,
1469 bool RHSIsKill, bool WantResult) {
1470 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1471 RHSIsKill, /*SetFlags=*/true, WantResult);
1474 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1475 bool LHSIsKill, unsigned RHSReg,
1477 AArch64_AM::ShiftExtendType ShiftType,
1478 uint64_t ShiftImm, bool WantResult) {
1479 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1480 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1484 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1485 const Value *LHS, const Value *RHS) {
1486 // Canonicalize immediates to the RHS first.
1487 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1488 std::swap(LHS, RHS);
1490 // Canonicalize mul by power-of-2 to the RHS.
1491 if (LHS->hasOneUse() && isValueAvailable(LHS))
1492 if (isMulPowOf2(LHS))
1493 std::swap(LHS, RHS);
1495 // Canonicalize shift immediate to the RHS.
1496 if (LHS->hasOneUse() && isValueAvailable(LHS))
1497 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1498 if (isa<ConstantInt>(SI->getOperand(1)))
1499 std::swap(LHS, RHS);
1501 unsigned LHSReg = getRegForValue(LHS);
1504 bool LHSIsKill = hasTrivialKill(LHS);
1506 unsigned ResultReg = 0;
1507 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1508 uint64_t Imm = C->getZExtValue();
1509 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1514 // Check if the mul can be folded into the instruction.
1515 if (RHS->hasOneUse() && isValueAvailable(RHS))
1516 if (isMulPowOf2(RHS)) {
1517 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1518 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1520 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1521 if (C->getValue().isPowerOf2())
1522 std::swap(MulLHS, MulRHS);
1524 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1525 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1527 unsigned RHSReg = getRegForValue(MulLHS);
1530 bool RHSIsKill = hasTrivialKill(MulLHS);
1531 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1532 RHSIsKill, ShiftVal);
1535 // Check if the shift can be folded into the instruction.
1536 if (RHS->hasOneUse() && isValueAvailable(RHS))
1537 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1538 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1539 uint64_t ShiftVal = C->getZExtValue();
1540 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1543 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1544 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1545 RHSIsKill, ShiftVal);
1548 unsigned RHSReg = getRegForValue(RHS);
1551 bool RHSIsKill = hasTrivialKill(RHS);
1553 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1554 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1555 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1556 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1557 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1562 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1563 unsigned LHSReg, bool LHSIsKill,
1565 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1566 "ISD nodes are not consecutive!");
1567 static const unsigned OpcTable[3][2] = {
1568 { AArch64::ANDWri, AArch64::ANDXri },
1569 { AArch64::ORRWri, AArch64::ORRXri },
1570 { AArch64::EORWri, AArch64::EORXri }
1572 const TargetRegisterClass *RC;
1575 switch (RetVT.SimpleTy) {
1582 unsigned Idx = ISDOpc - ISD::AND;
1583 Opc = OpcTable[Idx][0];
1584 RC = &AArch64::GPR32spRegClass;
1589 Opc = OpcTable[ISDOpc - ISD::AND][1];
1590 RC = &AArch64::GPR64spRegClass;
1595 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1598 unsigned ResultReg =
1599 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1600 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1601 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1602 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1603 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1608 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1609 unsigned LHSReg, bool LHSIsKill,
1610 unsigned RHSReg, bool RHSIsKill,
1611 uint64_t ShiftImm) {
1612 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1613 "ISD nodes are not consecutive!");
1614 static const unsigned OpcTable[3][2] = {
1615 { AArch64::ANDWrs, AArch64::ANDXrs },
1616 { AArch64::ORRWrs, AArch64::ORRXrs },
1617 { AArch64::EORWrs, AArch64::EORXrs }
1619 const TargetRegisterClass *RC;
1621 switch (RetVT.SimpleTy) {
1628 Opc = OpcTable[ISDOpc - ISD::AND][0];
1629 RC = &AArch64::GPR32RegClass;
1632 Opc = OpcTable[ISDOpc - ISD::AND][1];
1633 RC = &AArch64::GPR64RegClass;
1636 unsigned ResultReg =
1637 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1638 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1639 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1640 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1641 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1646 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1648 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1651 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1652 bool WantZExt, MachineMemOperand *MMO) {
1653 // Simplify this down to something we can handle.
1654 if (!simplifyAddress(Addr, VT))
1657 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1659 llvm_unreachable("Unexpected value type.");
1661 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1662 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1663 bool UseScaled = true;
1664 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1669 static const unsigned GPOpcTable[2][8][4] = {
1671 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1673 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1675 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1677 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1679 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1681 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1683 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1685 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1689 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1691 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1693 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1695 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1697 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1699 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1701 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1703 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1708 static const unsigned FPOpcTable[4][2] = {
1709 { AArch64::LDURSi, AArch64::LDURDi },
1710 { AArch64::LDRSui, AArch64::LDRDui },
1711 { AArch64::LDRSroX, AArch64::LDRDroX },
1712 { AArch64::LDRSroW, AArch64::LDRDroW }
1716 const TargetRegisterClass *RC;
1717 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1718 Addr.getOffsetReg();
1719 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1720 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1721 Addr.getExtendType() == AArch64_AM::SXTW)
1724 bool IsRet64Bit = RetVT == MVT::i64;
1725 switch (VT.SimpleTy) {
1727 llvm_unreachable("Unexpected value type.");
1728 case MVT::i1: // Intentional fall-through.
1730 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1731 RC = (IsRet64Bit && !WantZExt) ?
1732 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1735 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1736 RC = (IsRet64Bit && !WantZExt) ?
1737 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1740 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1741 RC = (IsRet64Bit && !WantZExt) ?
1742 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1745 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1746 RC = &AArch64::GPR64RegClass;
1749 Opc = FPOpcTable[Idx][0];
1750 RC = &AArch64::FPR32RegClass;
1753 Opc = FPOpcTable[Idx][1];
1754 RC = &AArch64::FPR64RegClass;
1758 // Create the base instruction, then add the operands.
1759 unsigned ResultReg = createResultReg(RC);
1760 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1761 TII.get(Opc), ResultReg);
1762 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1764 // Loading an i1 requires special handling.
1765 if (VT == MVT::i1) {
1766 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1767 assert(ANDReg && "Unexpected AND instruction emission failure.");
1771 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1772 // the 32bit reg to a 64bit reg.
1773 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1774 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1775 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1776 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1778 .addReg(ResultReg, getKillRegState(true))
1779 .addImm(AArch64::sub_32);
1785 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1787 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1791 return selectOperator(I, I->getOpcode());
1794 switch (I->getOpcode()) {
1796 llvm_unreachable("Unexpected instruction.");
1797 case Instruction::Add:
1798 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1800 case Instruction::Sub:
1801 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1807 updateValueMap(I, ResultReg);
1811 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1813 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1817 return selectOperator(I, I->getOpcode());
1820 switch (I->getOpcode()) {
1822 llvm_unreachable("Unexpected instruction.");
1823 case Instruction::And:
1824 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1826 case Instruction::Or:
1827 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1829 case Instruction::Xor:
1830 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1836 updateValueMap(I, ResultReg);
1840 bool AArch64FastISel::selectLoad(const Instruction *I) {
1842 // Verify we have a legal type before going any further. Currently, we handle
1843 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1844 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1845 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1846 cast<LoadInst>(I)->isAtomic())
1849 // See if we can handle this address.
1851 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1854 // Fold the following sign-/zero-extend into the load instruction.
1855 bool WantZExt = true;
1857 const Value *IntExtVal = nullptr;
1858 if (I->hasOneUse()) {
1859 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1860 if (isTypeSupported(ZE->getType(), RetVT))
1864 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1865 if (isTypeSupported(SE->getType(), RetVT))
1873 unsigned ResultReg =
1874 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1878 // There are a few different cases we have to handle, because the load or the
1879 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1880 // SelectionDAG. There is also an ordering issue when both instructions are in
1881 // different basic blocks.
1882 // 1.) The load instruction is selected by FastISel, but the integer extend
1883 // not. This usually happens when the integer extend is in a different
1884 // basic block and SelectionDAG took over for that basic block.
1885 // 2.) The load instruction is selected before the integer extend. This only
1886 // happens when the integer extend is in a different basic block.
1887 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1888 // by FastISel. This happens if there are instructions between the load
1889 // and the integer extend that couldn't be selected by FastISel.
1891 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1892 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1893 // it when it selects the integer extend.
1894 unsigned Reg = lookUpRegForValue(IntExtVal);
1896 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1898 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1899 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1900 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1902 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1906 updateValueMap(I, ResultReg);
1910 // The integer extend has already been emitted - delete all the instructions
1911 // that have been emitted by the integer extend lowering code and use the
1912 // result from the load instruction directly.
1914 auto *MI = MRI.getUniqueVRegDef(Reg);
1918 for (auto &Opnd : MI->uses()) {
1920 Reg = Opnd.getReg();
1924 MI->eraseFromParent();
1926 updateValueMap(IntExtVal, ResultReg);
1930 updateValueMap(I, ResultReg);
1934 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1935 MachineMemOperand *MMO) {
1936 // Simplify this down to something we can handle.
1937 if (!simplifyAddress(Addr, VT))
1940 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1942 llvm_unreachable("Unexpected value type.");
1944 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1945 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1946 bool UseScaled = true;
1947 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1952 static const unsigned OpcTable[4][6] = {
1953 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1954 AArch64::STURSi, AArch64::STURDi },
1955 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1956 AArch64::STRSui, AArch64::STRDui },
1957 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1958 AArch64::STRSroX, AArch64::STRDroX },
1959 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1960 AArch64::STRSroW, AArch64::STRDroW }
1964 bool VTIsi1 = false;
1965 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1966 Addr.getOffsetReg();
1967 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1968 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1969 Addr.getExtendType() == AArch64_AM::SXTW)
1972 switch (VT.SimpleTy) {
1973 default: llvm_unreachable("Unexpected value type.");
1974 case MVT::i1: VTIsi1 = true;
1975 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1976 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1977 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1978 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1979 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1980 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1983 // Storing an i1 requires special handling.
1984 if (VTIsi1 && SrcReg != AArch64::WZR) {
1985 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1986 assert(ANDReg && "Unexpected AND instruction emission failure.");
1989 // Create the base instruction, then add the operands.
1990 const MCInstrDesc &II = TII.get(Opc);
1991 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1992 MachineInstrBuilder MIB =
1993 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1994 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
1999 bool AArch64FastISel::selectStore(const Instruction *I) {
2001 const Value *Op0 = I->getOperand(0);
2002 // Verify we have a legal type before going any further. Currently, we handle
2003 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2004 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2005 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2006 cast<StoreInst>(I)->isAtomic())
2009 // Get the value to be stored into a register. Use the zero register directly
2010 // when possible to avoid an unnecessary copy and a wasted register.
2011 unsigned SrcReg = 0;
2012 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2014 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2015 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2016 if (CF->isZero() && !CF->isNegative()) {
2017 VT = MVT::getIntegerVT(VT.getSizeInBits());
2018 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2023 SrcReg = getRegForValue(Op0);
2028 // See if we can handle this address.
2030 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2033 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2038 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2040 case CmpInst::FCMP_ONE:
2041 case CmpInst::FCMP_UEQ:
2043 // AL is our "false" for now. The other two need more compares.
2044 return AArch64CC::AL;
2045 case CmpInst::ICMP_EQ:
2046 case CmpInst::FCMP_OEQ:
2047 return AArch64CC::EQ;
2048 case CmpInst::ICMP_SGT:
2049 case CmpInst::FCMP_OGT:
2050 return AArch64CC::GT;
2051 case CmpInst::ICMP_SGE:
2052 case CmpInst::FCMP_OGE:
2053 return AArch64CC::GE;
2054 case CmpInst::ICMP_UGT:
2055 case CmpInst::FCMP_UGT:
2056 return AArch64CC::HI;
2057 case CmpInst::FCMP_OLT:
2058 return AArch64CC::MI;
2059 case CmpInst::ICMP_ULE:
2060 case CmpInst::FCMP_OLE:
2061 return AArch64CC::LS;
2062 case CmpInst::FCMP_ORD:
2063 return AArch64CC::VC;
2064 case CmpInst::FCMP_UNO:
2065 return AArch64CC::VS;
2066 case CmpInst::FCMP_UGE:
2067 return AArch64CC::PL;
2068 case CmpInst::ICMP_SLT:
2069 case CmpInst::FCMP_ULT:
2070 return AArch64CC::LT;
2071 case CmpInst::ICMP_SLE:
2072 case CmpInst::FCMP_ULE:
2073 return AArch64CC::LE;
2074 case CmpInst::FCMP_UNE:
2075 case CmpInst::ICMP_NE:
2076 return AArch64CC::NE;
2077 case CmpInst::ICMP_UGE:
2078 return AArch64CC::HS;
2079 case CmpInst::ICMP_ULT:
2080 return AArch64CC::LO;
2084 /// \brief Try to emit a combined compare-and-branch instruction.
2085 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2086 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2087 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2088 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2090 const Value *LHS = CI->getOperand(0);
2091 const Value *RHS = CI->getOperand(1);
2093 Type *Ty = LHS->getType();
2094 if (!Ty->isIntegerTy())
2097 unsigned BW = cast<IntegerType>(Ty)->getBitWidth();
2098 if (BW != 1 && BW != 8 && BW != 16 && BW != 32 && BW != 64)
2101 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2102 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2104 // Try to take advantage of fallthrough opportunities.
2105 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2106 std::swap(TBB, FBB);
2107 Predicate = CmpInst::getInversePredicate(Predicate);
2112 if ((Predicate == CmpInst::ICMP_EQ) || (Predicate == CmpInst::ICMP_NE)) {
2113 if (const auto *C = dyn_cast<ConstantInt>(LHS))
2114 if (C->isNullValue())
2115 std::swap(LHS, RHS);
2117 if (!isa<ConstantInt>(RHS))
2120 if (!cast<ConstantInt>(RHS)->isNullValue())
2123 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2124 if (AI->getOpcode() == Instruction::And) {
2125 const Value *AndLHS = AI->getOperand(0);
2126 const Value *AndRHS = AI->getOperand(1);
2128 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2129 if (C->getValue().isPowerOf2())
2130 std::swap(AndLHS, AndRHS);
2132 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2133 if (C->getValue().isPowerOf2()) {
2134 TestBit = C->getValue().logBase2();
2138 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2139 } else if (Predicate == CmpInst::ICMP_SLT) {
2140 if (!isa<ConstantInt>(RHS))
2143 if (!cast<ConstantInt>(RHS)->isNullValue())
2148 } else if (Predicate == CmpInst::ICMP_SGT) {
2149 if (!isa<ConstantInt>(RHS))
2152 if (cast<ConstantInt>(RHS)->getValue() != -1)
2160 static const unsigned OpcTable[2][2][2] = {
2161 { {AArch64::CBZW, AArch64::CBZX },
2162 {AArch64::CBNZW, AArch64::CBNZX} },
2163 { {AArch64::TBZW, AArch64::TBZX },
2164 {AArch64::TBNZW, AArch64::TBNZX} }
2167 bool IsBitTest = TestBit != -1;
2168 bool Is64Bit = BW == 64;
2169 if (TestBit < 32 && TestBit >= 0)
2172 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2173 const MCInstrDesc &II = TII.get(Opc);
2175 unsigned SrcReg = getRegForValue(LHS);
2178 bool SrcIsKill = hasTrivialKill(LHS);
2180 if (BW == 64 && !Is64Bit)
2181 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2184 // Emit the combined compare and branch instruction.
2185 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2186 MachineInstrBuilder MIB =
2187 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2188 .addReg(SrcReg, getKillRegState(SrcIsKill));
2190 MIB.addImm(TestBit);
2193 // Obtain the branch weight and add the TrueBB to the successor list.
2194 uint32_t BranchWeight = 0;
2196 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2197 TBB->getBasicBlock());
2198 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2199 fastEmitBranch(FBB, DbgLoc);
2204 bool AArch64FastISel::selectBranch(const Instruction *I) {
2205 const BranchInst *BI = cast<BranchInst>(I);
2206 if (BI->isUnconditional()) {
2207 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2208 fastEmitBranch(MSucc, BI->getDebugLoc());
2212 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2213 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2215 AArch64CC::CondCode CC = AArch64CC::NE;
2216 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2217 if (CI->hasOneUse() && isValueAvailable(CI)) {
2218 // Try to optimize or fold the cmp.
2219 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2220 switch (Predicate) {
2223 case CmpInst::FCMP_FALSE:
2224 fastEmitBranch(FBB, DbgLoc);
2226 case CmpInst::FCMP_TRUE:
2227 fastEmitBranch(TBB, DbgLoc);
2231 // Try to emit a combined compare-and-branch first.
2232 if (emitCompareAndBranch(BI))
2235 // Try to take advantage of fallthrough opportunities.
2236 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2237 std::swap(TBB, FBB);
2238 Predicate = CmpInst::getInversePredicate(Predicate);
2242 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2245 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2247 CC = getCompareCC(Predicate);
2248 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2249 switch (Predicate) {
2252 case CmpInst::FCMP_UEQ:
2253 ExtraCC = AArch64CC::EQ;
2256 case CmpInst::FCMP_ONE:
2257 ExtraCC = AArch64CC::MI;
2261 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2263 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2264 if (ExtraCC != AArch64CC::AL) {
2265 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2271 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2275 // Obtain the branch weight and add the TrueBB to the successor list.
2276 uint32_t BranchWeight = 0;
2278 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2279 TBB->getBasicBlock());
2280 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2282 fastEmitBranch(FBB, DbgLoc);
2285 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2287 if (TI->hasOneUse() && isValueAvailable(TI) &&
2288 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2289 unsigned CondReg = getRegForValue(TI->getOperand(0));
2292 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2294 // Issue an extract_subreg to get the lower 32-bits.
2295 if (SrcVT == MVT::i64) {
2296 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2301 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2302 assert(ANDReg && "Unexpected AND instruction emission failure.");
2303 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2305 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2306 std::swap(TBB, FBB);
2309 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2313 // Obtain the branch weight and add the TrueBB to the successor list.
2314 uint32_t BranchWeight = 0;
2316 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2317 TBB->getBasicBlock());
2318 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2320 fastEmitBranch(FBB, DbgLoc);
2323 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2324 uint64_t Imm = CI->getZExtValue();
2325 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2326 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2329 // Obtain the branch weight and add the target to the successor list.
2330 uint32_t BranchWeight = 0;
2332 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2333 Target->getBasicBlock());
2334 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2336 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2337 // Fake request the condition, otherwise the intrinsic might be completely
2339 unsigned CondReg = getRegForValue(BI->getCondition());
2344 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2348 // Obtain the branch weight and add the TrueBB to the successor list.
2349 uint32_t BranchWeight = 0;
2351 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2352 TBB->getBasicBlock());
2353 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2355 fastEmitBranch(FBB, DbgLoc);
2359 unsigned CondReg = getRegForValue(BI->getCondition());
2362 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2364 // We've been divorced from our compare! Our block was split, and
2365 // now our compare lives in a predecessor block. We musn't
2366 // re-compare here, as the children of the compare aren't guaranteed
2367 // live across the block boundary (we *could* check for this).
2368 // Regardless, the compare has been done in the predecessor block,
2369 // and it left a value for us in a virtual register. Ergo, we test
2370 // the one-bit value left in the virtual register.
2371 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2373 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2374 std::swap(TBB, FBB);
2378 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2382 // Obtain the branch weight and add the TrueBB to the successor list.
2383 uint32_t BranchWeight = 0;
2385 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2386 TBB->getBasicBlock());
2387 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2389 fastEmitBranch(FBB, DbgLoc);
2393 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2394 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2395 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2399 // Emit the indirect branch.
2400 const MCInstrDesc &II = TII.get(AArch64::BR);
2401 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2402 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2404 // Make sure the CFG is up-to-date.
2405 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2406 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2411 bool AArch64FastISel::selectCmp(const Instruction *I) {
2412 const CmpInst *CI = cast<CmpInst>(I);
2414 // Try to optimize or fold the cmp.
2415 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2416 unsigned ResultReg = 0;
2417 switch (Predicate) {
2420 case CmpInst::FCMP_FALSE:
2421 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2423 TII.get(TargetOpcode::COPY), ResultReg)
2424 .addReg(AArch64::WZR, getKillRegState(true));
2426 case CmpInst::FCMP_TRUE:
2427 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2432 updateValueMap(I, ResultReg);
2437 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2440 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2442 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2443 // condition codes are inverted, because they are used by CSINC.
2444 static unsigned CondCodeTable[2][2] = {
2445 { AArch64CC::NE, AArch64CC::VC },
2446 { AArch64CC::PL, AArch64CC::LE }
2448 unsigned *CondCodes = nullptr;
2449 switch (Predicate) {
2452 case CmpInst::FCMP_UEQ:
2453 CondCodes = &CondCodeTable[0][0];
2455 case CmpInst::FCMP_ONE:
2456 CondCodes = &CondCodeTable[1][0];
2461 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2462 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2464 .addReg(AArch64::WZR, getKillRegState(true))
2465 .addReg(AArch64::WZR, getKillRegState(true))
2466 .addImm(CondCodes[0]);
2467 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2469 .addReg(TmpReg1, getKillRegState(true))
2470 .addReg(AArch64::WZR, getKillRegState(true))
2471 .addImm(CondCodes[1]);
2473 updateValueMap(I, ResultReg);
2477 // Now set a register based on the comparison.
2478 AArch64CC::CondCode CC = getCompareCC(Predicate);
2479 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2480 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2481 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2483 .addReg(AArch64::WZR, getKillRegState(true))
2484 .addReg(AArch64::WZR, getKillRegState(true))
2485 .addImm(invertedCC);
2487 updateValueMap(I, ResultReg);
2491 bool AArch64FastISel::selectSelect(const Instruction *I) {
2492 const SelectInst *SI = cast<SelectInst>(I);
2494 EVT DestEVT = TLI.getValueType(SI->getType(), true);
2495 if (!DestEVT.isSimple())
2498 MVT DestVT = DestEVT.getSimpleVT();
2499 if (DestVT != MVT::i32 && DestVT != MVT::i64 && DestVT != MVT::f32 &&
2504 const TargetRegisterClass *RC = nullptr;
2505 switch (DestVT.SimpleTy) {
2506 default: return false;
2508 SelectOpc = AArch64::CSELWr; RC = &AArch64::GPR32RegClass; break;
2510 SelectOpc = AArch64::CSELXr; RC = &AArch64::GPR64RegClass; break;
2512 SelectOpc = AArch64::FCSELSrrr; RC = &AArch64::FPR32RegClass; break;
2514 SelectOpc = AArch64::FCSELDrrr; RC = &AArch64::FPR64RegClass; break;
2517 const Value *Cond = SI->getCondition();
2518 bool NeedTest = true;
2519 AArch64CC::CondCode CC = AArch64CC::NE;
2520 if (foldXALUIntrinsic(CC, I, Cond))
2523 unsigned CondReg = getRegForValue(Cond);
2526 bool CondIsKill = hasTrivialKill(Cond);
2529 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2530 assert(ANDReg && "Unexpected AND instruction emission failure.");
2531 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2534 unsigned TrueReg = getRegForValue(SI->getTrueValue());
2535 bool TrueIsKill = hasTrivialKill(SI->getTrueValue());
2537 unsigned FalseReg = getRegForValue(SI->getFalseValue());
2538 bool FalseIsKill = hasTrivialKill(SI->getFalseValue());
2540 if (!TrueReg || !FalseReg)
2543 unsigned ResultReg = fastEmitInst_rri(SelectOpc, RC, TrueReg, TrueIsKill,
2544 FalseReg, FalseIsKill, CC);
2545 updateValueMap(I, ResultReg);
2549 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2550 Value *V = I->getOperand(0);
2551 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2554 unsigned Op = getRegForValue(V);
2558 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2559 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2560 ResultReg).addReg(Op);
2561 updateValueMap(I, ResultReg);
2565 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2566 Value *V = I->getOperand(0);
2567 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2570 unsigned Op = getRegForValue(V);
2574 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2575 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2576 ResultReg).addReg(Op);
2577 updateValueMap(I, ResultReg);
2581 // FPToUI and FPToSI
2582 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2584 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2587 unsigned SrcReg = getRegForValue(I->getOperand(0));
2591 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2592 if (SrcVT == MVT::f128)
2596 if (SrcVT == MVT::f64) {
2598 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2600 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2603 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2605 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2607 unsigned ResultReg = createResultReg(
2608 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2609 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2611 updateValueMap(I, ResultReg);
2615 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2617 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2619 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2620 "Unexpected value type.");
2622 unsigned SrcReg = getRegForValue(I->getOperand(0));
2625 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2627 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2629 // Handle sign-extension.
2630 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2632 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2639 if (SrcVT == MVT::i64) {
2641 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2643 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2646 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2648 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2651 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2653 updateValueMap(I, ResultReg);
2657 bool AArch64FastISel::fastLowerArguments() {
2658 if (!FuncInfo.CanLowerReturn)
2661 const Function *F = FuncInfo.Fn;
2665 CallingConv::ID CC = F->getCallingConv();
2666 if (CC != CallingConv::C)
2669 // Only handle simple cases of up to 8 GPR and FPR each.
2670 unsigned GPRCnt = 0;
2671 unsigned FPRCnt = 0;
2673 for (auto const &Arg : F->args()) {
2674 // The first argument is at index 1.
2676 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2677 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2678 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2679 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2682 Type *ArgTy = Arg.getType();
2683 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2686 EVT ArgVT = TLI.getValueType(ArgTy);
2687 if (!ArgVT.isSimple())
2690 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2691 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2694 if (VT.isVector() &&
2695 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2698 if (VT >= MVT::i1 && VT <= MVT::i64)
2700 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2701 VT.is128BitVector())
2706 if (GPRCnt > 8 || FPRCnt > 8)
2710 static const MCPhysReg Registers[6][8] = {
2711 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2712 AArch64::W5, AArch64::W6, AArch64::W7 },
2713 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2714 AArch64::X5, AArch64::X6, AArch64::X7 },
2715 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2716 AArch64::H5, AArch64::H6, AArch64::H7 },
2717 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2718 AArch64::S5, AArch64::S6, AArch64::S7 },
2719 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2720 AArch64::D5, AArch64::D6, AArch64::D7 },
2721 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2722 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2725 unsigned GPRIdx = 0;
2726 unsigned FPRIdx = 0;
2727 for (auto const &Arg : F->args()) {
2728 MVT VT = TLI.getSimpleValueType(Arg.getType());
2730 const TargetRegisterClass *RC;
2731 if (VT >= MVT::i1 && VT <= MVT::i32) {
2732 SrcReg = Registers[0][GPRIdx++];
2733 RC = &AArch64::GPR32RegClass;
2735 } else if (VT == MVT::i64) {
2736 SrcReg = Registers[1][GPRIdx++];
2737 RC = &AArch64::GPR64RegClass;
2738 } else if (VT == MVT::f16) {
2739 SrcReg = Registers[2][FPRIdx++];
2740 RC = &AArch64::FPR16RegClass;
2741 } else if (VT == MVT::f32) {
2742 SrcReg = Registers[3][FPRIdx++];
2743 RC = &AArch64::FPR32RegClass;
2744 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2745 SrcReg = Registers[4][FPRIdx++];
2746 RC = &AArch64::FPR64RegClass;
2747 } else if (VT.is128BitVector()) {
2748 SrcReg = Registers[5][FPRIdx++];
2749 RC = &AArch64::FPR128RegClass;
2751 llvm_unreachable("Unexpected value type.");
2753 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2754 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2755 // Without this, EmitLiveInCopies may eliminate the livein if its only
2756 // use is a bitcast (which isn't turned into an instruction).
2757 unsigned ResultReg = createResultReg(RC);
2758 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2759 TII.get(TargetOpcode::COPY), ResultReg)
2760 .addReg(DstReg, getKillRegState(true));
2761 updateValueMap(&Arg, ResultReg);
2766 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2767 SmallVectorImpl<MVT> &OutVTs,
2768 unsigned &NumBytes) {
2769 CallingConv::ID CC = CLI.CallConv;
2770 SmallVector<CCValAssign, 16> ArgLocs;
2771 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2772 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2774 // Get a count of how many bytes are to be pushed on the stack.
2775 NumBytes = CCInfo.getNextStackOffset();
2777 // Issue CALLSEQ_START
2778 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2779 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2782 // Process the args.
2783 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2784 CCValAssign &VA = ArgLocs[i];
2785 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2786 MVT ArgVT = OutVTs[VA.getValNo()];
2788 unsigned ArgReg = getRegForValue(ArgVal);
2792 // Handle arg promotion: SExt, ZExt, AExt.
2793 switch (VA.getLocInfo()) {
2794 case CCValAssign::Full:
2796 case CCValAssign::SExt: {
2797 MVT DestVT = VA.getLocVT();
2799 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2804 case CCValAssign::AExt:
2805 // Intentional fall-through.
2806 case CCValAssign::ZExt: {
2807 MVT DestVT = VA.getLocVT();
2809 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2815 llvm_unreachable("Unknown arg promotion!");
2818 // Now copy/store arg to correct locations.
2819 if (VA.isRegLoc() && !VA.needsCustom()) {
2820 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2821 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2822 CLI.OutRegs.push_back(VA.getLocReg());
2823 } else if (VA.needsCustom()) {
2824 // FIXME: Handle custom args.
2827 assert(VA.isMemLoc() && "Assuming store on stack.");
2829 // Don't emit stores for undef values.
2830 if (isa<UndefValue>(ArgVal))
2833 // Need to store on the stack.
2834 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2836 unsigned BEAlign = 0;
2837 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2838 BEAlign = 8 - ArgSize;
2841 Addr.setKind(Address::RegBase);
2842 Addr.setReg(AArch64::SP);
2843 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2845 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2846 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2847 MachinePointerInfo::getStack(Addr.getOffset()),
2848 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2850 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2857 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2858 unsigned NumBytes) {
2859 CallingConv::ID CC = CLI.CallConv;
2861 // Issue CALLSEQ_END
2862 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2863 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2864 .addImm(NumBytes).addImm(0);
2866 // Now the return value.
2867 if (RetVT != MVT::isVoid) {
2868 SmallVector<CCValAssign, 16> RVLocs;
2869 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2870 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2872 // Only handle a single return value.
2873 if (RVLocs.size() != 1)
2876 // Copy all of the result registers out of their specified physreg.
2877 MVT CopyVT = RVLocs[0].getValVT();
2878 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2879 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2880 TII.get(TargetOpcode::COPY), ResultReg)
2881 .addReg(RVLocs[0].getLocReg());
2882 CLI.InRegs.push_back(RVLocs[0].getLocReg());
2884 CLI.ResultReg = ResultReg;
2885 CLI.NumResultRegs = 1;
2891 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2892 CallingConv::ID CC = CLI.CallConv;
2893 bool IsTailCall = CLI.IsTailCall;
2894 bool IsVarArg = CLI.IsVarArg;
2895 const Value *Callee = CLI.Callee;
2896 const char *SymName = CLI.SymName;
2898 if (!Callee && !SymName)
2901 // Allow SelectionDAG isel to handle tail calls.
2905 CodeModel::Model CM = TM.getCodeModel();
2906 // Only support the small and large code model.
2907 if (CM != CodeModel::Small && CM != CodeModel::Large)
2910 // FIXME: Add large code model support for ELF.
2911 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2914 // Let SDISel handle vararg functions.
2918 // FIXME: Only handle *simple* calls for now.
2920 if (CLI.RetTy->isVoidTy())
2921 RetVT = MVT::isVoid;
2922 else if (!isTypeLegal(CLI.RetTy, RetVT))
2925 for (auto Flag : CLI.OutFlags)
2926 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2929 // Set up the argument vectors.
2930 SmallVector<MVT, 16> OutVTs;
2931 OutVTs.reserve(CLI.OutVals.size());
2933 for (auto *Val : CLI.OutVals) {
2935 if (!isTypeLegal(Val->getType(), VT) &&
2936 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2939 // We don't handle vector parameters yet.
2940 if (VT.isVector() || VT.getSizeInBits() > 64)
2943 OutVTs.push_back(VT);
2947 if (Callee && !computeCallAddress(Callee, Addr))
2950 // Handle the arguments now that we've gotten them.
2952 if (!processCallArgs(CLI, OutVTs, NumBytes))
2956 MachineInstrBuilder MIB;
2957 if (CM == CodeModel::Small) {
2958 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2959 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2961 MIB.addExternalSymbol(SymName, 0);
2962 else if (Addr.getGlobalValue())
2963 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2964 else if (Addr.getReg()) {
2965 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2970 unsigned CallReg = 0;
2972 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2973 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2975 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2977 CallReg = createResultReg(&AArch64::GPR64RegClass);
2978 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
2981 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
2983 } else if (Addr.getGlobalValue())
2984 CallReg = materializeGV(Addr.getGlobalValue());
2985 else if (Addr.getReg())
2986 CallReg = Addr.getReg();
2991 const MCInstrDesc &II = TII.get(AArch64::BLR);
2992 CallReg = constrainOperandRegClass(II, CallReg, 0);
2993 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
2996 // Add implicit physical register uses to the call.
2997 for (auto Reg : CLI.OutRegs)
2998 MIB.addReg(Reg, RegState::Implicit);
3000 // Add a register mask with the call-preserved registers.
3001 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3002 MIB.addRegMask(TRI.getCallPreservedMask(CC));
3006 // Finish off the call including any return values.
3007 return finishCall(CLI, RetVT, NumBytes);
3010 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3012 return Len / Alignment <= 4;
3017 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3018 uint64_t Len, unsigned Alignment) {
3019 // Make sure we don't bloat code by inlining very large memcpy's.
3020 if (!isMemCpySmall(Len, Alignment))
3023 int64_t UnscaledOffset = 0;
3024 Address OrigDest = Dest;
3025 Address OrigSrc = Src;
3029 if (!Alignment || Alignment >= 8) {
3040 // Bound based on alignment.
3041 if (Len >= 4 && Alignment == 4)
3043 else if (Len >= 2 && Alignment == 2)
3050 unsigned ResultReg = emitLoad(VT, VT, Src);
3054 if (!emitStore(VT, ResultReg, Dest))
3057 int64_t Size = VT.getSizeInBits() / 8;
3059 UnscaledOffset += Size;
3061 // We need to recompute the unscaled offset for each iteration.
3062 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3063 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3069 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3070 /// into the user. The condition code will only be updated on success.
3071 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3072 const Instruction *I,
3073 const Value *Cond) {
3074 if (!isa<ExtractValueInst>(Cond))
3077 const auto *EV = cast<ExtractValueInst>(Cond);
3078 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3081 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3083 const Function *Callee = II->getCalledFunction();
3085 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3086 if (!isTypeLegal(RetTy, RetVT))
3089 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3092 const Value *LHS = II->getArgOperand(0);
3093 const Value *RHS = II->getArgOperand(1);
3095 // Canonicalize immediate to the RHS.
3096 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3097 isCommutativeIntrinsic(II))
3098 std::swap(LHS, RHS);
3100 // Simplify multiplies.
3101 unsigned IID = II->getIntrinsicID();
3105 case Intrinsic::smul_with_overflow:
3106 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3107 if (C->getValue() == 2)
3108 IID = Intrinsic::sadd_with_overflow;
3110 case Intrinsic::umul_with_overflow:
3111 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3112 if (C->getValue() == 2)
3113 IID = Intrinsic::uadd_with_overflow;
3117 AArch64CC::CondCode TmpCC;
3121 case Intrinsic::sadd_with_overflow:
3122 case Intrinsic::ssub_with_overflow:
3123 TmpCC = AArch64CC::VS;
3125 case Intrinsic::uadd_with_overflow:
3126 TmpCC = AArch64CC::HS;
3128 case Intrinsic::usub_with_overflow:
3129 TmpCC = AArch64CC::LO;
3131 case Intrinsic::smul_with_overflow:
3132 case Intrinsic::umul_with_overflow:
3133 TmpCC = AArch64CC::NE;
3137 // Check if both instructions are in the same basic block.
3138 if (!isValueAvailable(II))
3141 // Make sure nothing is in the way
3142 BasicBlock::const_iterator Start = I;
3143 BasicBlock::const_iterator End = II;
3144 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3145 // We only expect extractvalue instructions between the intrinsic and the
3146 // instruction to be selected.
3147 if (!isa<ExtractValueInst>(Itr))
3150 // Check that the extractvalue operand comes from the intrinsic.
3151 const auto *EVI = cast<ExtractValueInst>(Itr);
3152 if (EVI->getAggregateOperand() != II)
3160 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3161 // FIXME: Handle more intrinsics.
3162 switch (II->getIntrinsicID()) {
3163 default: return false;
3164 case Intrinsic::frameaddress: {
3165 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3166 MFI->setFrameAddressIsTaken(true);
3168 const AArch64RegisterInfo *RegInfo =
3169 static_cast<const AArch64RegisterInfo *>(
3170 TM.getSubtargetImpl()->getRegisterInfo());
3171 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3172 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3173 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3174 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3175 // Recursively load frame address
3181 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3183 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3184 SrcReg, /*IsKill=*/true, 0);
3185 assert(DestReg && "Unexpected LDR instruction emission failure.");
3189 updateValueMap(II, SrcReg);
3192 case Intrinsic::memcpy:
3193 case Intrinsic::memmove: {
3194 const auto *MTI = cast<MemTransferInst>(II);
3195 // Don't handle volatile.
3196 if (MTI->isVolatile())
3199 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3200 // we would emit dead code because we don't currently handle memmoves.
3201 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3202 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3203 // Small memcpy's are common enough that we want to do them without a call
3205 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3206 unsigned Alignment = MTI->getAlignment();
3207 if (isMemCpySmall(Len, Alignment)) {
3209 if (!computeAddress(MTI->getRawDest(), Dest) ||
3210 !computeAddress(MTI->getRawSource(), Src))
3212 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3217 if (!MTI->getLength()->getType()->isIntegerTy(64))
3220 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3221 // Fast instruction selection doesn't support the special
3225 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3226 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3228 case Intrinsic::memset: {
3229 const MemSetInst *MSI = cast<MemSetInst>(II);
3230 // Don't handle volatile.
3231 if (MSI->isVolatile())
3234 if (!MSI->getLength()->getType()->isIntegerTy(64))
3237 if (MSI->getDestAddressSpace() > 255)
3238 // Fast instruction selection doesn't support the special
3242 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3244 case Intrinsic::sin:
3245 case Intrinsic::cos:
3246 case Intrinsic::pow: {
3248 if (!isTypeLegal(II->getType(), RetVT))
3251 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3254 static const RTLIB::Libcall LibCallTable[3][2] = {
3255 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3256 { RTLIB::COS_F32, RTLIB::COS_F64 },
3257 { RTLIB::POW_F32, RTLIB::POW_F64 }
3260 bool Is64Bit = RetVT == MVT::f64;
3261 switch (II->getIntrinsicID()) {
3263 llvm_unreachable("Unexpected intrinsic.");
3264 case Intrinsic::sin:
3265 LC = LibCallTable[0][Is64Bit];
3267 case Intrinsic::cos:
3268 LC = LibCallTable[1][Is64Bit];
3270 case Intrinsic::pow:
3271 LC = LibCallTable[2][Is64Bit];
3276 Args.reserve(II->getNumArgOperands());
3278 // Populate the argument list.
3279 for (auto &Arg : II->arg_operands()) {
3282 Entry.Ty = Arg->getType();
3283 Args.push_back(Entry);
3286 CallLoweringInfo CLI;
3287 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3288 TLI.getLibcallName(LC), std::move(Args));
3289 if (!lowerCallTo(CLI))
3291 updateValueMap(II, CLI.ResultReg);
3294 case Intrinsic::trap: {
3295 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3299 case Intrinsic::sqrt: {
3300 Type *RetTy = II->getCalledFunction()->getReturnType();
3303 if (!isTypeLegal(RetTy, VT))
3306 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3309 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3311 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3315 updateValueMap(II, ResultReg);
3318 case Intrinsic::sadd_with_overflow:
3319 case Intrinsic::uadd_with_overflow:
3320 case Intrinsic::ssub_with_overflow:
3321 case Intrinsic::usub_with_overflow:
3322 case Intrinsic::smul_with_overflow:
3323 case Intrinsic::umul_with_overflow: {
3324 // This implements the basic lowering of the xalu with overflow intrinsics.
3325 const Function *Callee = II->getCalledFunction();
3326 auto *Ty = cast<StructType>(Callee->getReturnType());
3327 Type *RetTy = Ty->getTypeAtIndex(0U);
3330 if (!isTypeLegal(RetTy, VT))
3333 if (VT != MVT::i32 && VT != MVT::i64)
3336 const Value *LHS = II->getArgOperand(0);
3337 const Value *RHS = II->getArgOperand(1);
3338 // Canonicalize immediate to the RHS.
3339 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3340 isCommutativeIntrinsic(II))
3341 std::swap(LHS, RHS);
3343 // Simplify multiplies.
3344 unsigned IID = II->getIntrinsicID();
3348 case Intrinsic::smul_with_overflow:
3349 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3350 if (C->getValue() == 2) {
3351 IID = Intrinsic::sadd_with_overflow;
3355 case Intrinsic::umul_with_overflow:
3356 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3357 if (C->getValue() == 2) {
3358 IID = Intrinsic::uadd_with_overflow;
3364 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3365 AArch64CC::CondCode CC = AArch64CC::Invalid;
3367 default: llvm_unreachable("Unexpected intrinsic!");
3368 case Intrinsic::sadd_with_overflow:
3369 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3372 case Intrinsic::uadd_with_overflow:
3373 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3376 case Intrinsic::ssub_with_overflow:
3377 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3380 case Intrinsic::usub_with_overflow:
3381 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3384 case Intrinsic::smul_with_overflow: {
3386 unsigned LHSReg = getRegForValue(LHS);
3389 bool LHSIsKill = hasTrivialKill(LHS);
3391 unsigned RHSReg = getRegForValue(RHS);
3394 bool RHSIsKill = hasTrivialKill(RHS);
3396 if (VT == MVT::i32) {
3397 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3398 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3399 /*IsKill=*/false, 32);
3400 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3402 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3404 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3405 AArch64_AM::ASR, 31, /*WantResult=*/false);
3407 assert(VT == MVT::i64 && "Unexpected value type.");
3408 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3409 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3411 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3412 AArch64_AM::ASR, 63, /*WantResult=*/false);
3416 case Intrinsic::umul_with_overflow: {
3418 unsigned LHSReg = getRegForValue(LHS);
3421 bool LHSIsKill = hasTrivialKill(LHS);
3423 unsigned RHSReg = getRegForValue(RHS);
3426 bool RHSIsKill = hasTrivialKill(RHS);
3428 if (VT == MVT::i32) {
3429 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3430 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3431 /*IsKill=*/false, AArch64_AM::LSR, 32,
3432 /*WantResult=*/false);
3433 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3436 assert(VT == MVT::i64 && "Unexpected value type.");
3437 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3438 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3440 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3441 /*IsKill=*/false, /*WantResult=*/false);
3448 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3449 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3450 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3453 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3454 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3455 /*IsKill=*/true, getInvertedCondCode(CC));
3457 assert((ResultReg1 + 1) == ResultReg2 &&
3458 "Nonconsecutive result registers.");
3459 updateValueMap(II, ResultReg1, 2);
3466 bool AArch64FastISel::selectRet(const Instruction *I) {
3467 const ReturnInst *Ret = cast<ReturnInst>(I);
3468 const Function &F = *I->getParent()->getParent();
3470 if (!FuncInfo.CanLowerReturn)
3476 // Build a list of return value registers.
3477 SmallVector<unsigned, 4> RetRegs;
3479 if (Ret->getNumOperands() > 0) {
3480 CallingConv::ID CC = F.getCallingConv();
3481 SmallVector<ISD::OutputArg, 4> Outs;
3482 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3484 // Analyze operands of the call, assigning locations to each operand.
3485 SmallVector<CCValAssign, 16> ValLocs;
3486 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3487 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3488 : RetCC_AArch64_AAPCS;
3489 CCInfo.AnalyzeReturn(Outs, RetCC);
3491 // Only handle a single return value for now.
3492 if (ValLocs.size() != 1)
3495 CCValAssign &VA = ValLocs[0];
3496 const Value *RV = Ret->getOperand(0);
3498 // Don't bother handling odd stuff for now.
3499 if ((VA.getLocInfo() != CCValAssign::Full) &&
3500 (VA.getLocInfo() != CCValAssign::BCvt))
3503 // Only handle register returns for now.
3507 unsigned Reg = getRegForValue(RV);
3511 unsigned SrcReg = Reg + VA.getValNo();
3512 unsigned DestReg = VA.getLocReg();
3513 // Avoid a cross-class copy. This is very unlikely.
3514 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3517 EVT RVEVT = TLI.getValueType(RV->getType());
3518 if (!RVEVT.isSimple())
3521 // Vectors (of > 1 lane) in big endian need tricky handling.
3522 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3523 !Subtarget->isLittleEndian())
3526 MVT RVVT = RVEVT.getSimpleVT();
3527 if (RVVT == MVT::f128)
3530 MVT DestVT = VA.getValVT();
3531 // Special handling for extended integers.
3532 if (RVVT != DestVT) {
3533 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3536 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3539 bool IsZExt = Outs[0].Flags.isZExt();
3540 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3546 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3547 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3549 // Add register to return instruction.
3550 RetRegs.push_back(VA.getLocReg());
3553 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3554 TII.get(AArch64::RET_ReallyLR));
3555 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3556 MIB.addReg(RetRegs[i], RegState::Implicit);
3560 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3561 Type *DestTy = I->getType();
3562 Value *Op = I->getOperand(0);
3563 Type *SrcTy = Op->getType();
3565 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3566 EVT DestEVT = TLI.getValueType(DestTy, true);
3567 if (!SrcEVT.isSimple())
3569 if (!DestEVT.isSimple())
3572 MVT SrcVT = SrcEVT.getSimpleVT();
3573 MVT DestVT = DestEVT.getSimpleVT();
3575 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3578 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3582 unsigned SrcReg = getRegForValue(Op);
3585 bool SrcIsKill = hasTrivialKill(Op);
3587 // If we're truncating from i64 to a smaller non-legal type then generate an
3588 // AND. Otherwise, we know the high bits are undefined and a truncate only
3589 // generate a COPY. We cannot mark the source register also as result
3590 // register, because this can incorrectly transfer the kill flag onto the
3593 if (SrcVT == MVT::i64) {
3595 switch (DestVT.SimpleTy) {
3597 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3609 // Issue an extract_subreg to get the lower 32-bits.
3610 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3612 // Create the AND instruction which performs the actual truncation.
3613 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3614 assert(ResultReg && "Unexpected AND instruction emission failure.");
3616 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3617 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3618 TII.get(TargetOpcode::COPY), ResultReg)
3619 .addReg(SrcReg, getKillRegState(SrcIsKill));
3622 updateValueMap(I, ResultReg);
3626 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3627 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3628 DestVT == MVT::i64) &&
3629 "Unexpected value type.");
3630 // Handle i8 and i16 as i32.
3631 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3635 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3636 assert(ResultReg && "Unexpected AND instruction emission failure.");
3637 if (DestVT == MVT::i64) {
3638 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3639 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3640 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3641 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3642 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3645 .addImm(AArch64::sub_32);
3650 if (DestVT == MVT::i64) {
3651 // FIXME: We're SExt i1 to i64.
3654 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3655 /*TODO:IsKill=*/false, 0, 0);
3659 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3660 unsigned Op1, bool Op1IsKill) {
3662 switch (RetVT.SimpleTy) {
3668 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3670 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3673 const TargetRegisterClass *RC =
3674 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3675 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3676 /*IsKill=*/ZReg, true);
3679 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3680 unsigned Op1, bool Op1IsKill) {
3681 if (RetVT != MVT::i64)
3684 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3685 Op0, Op0IsKill, Op1, Op1IsKill,
3686 AArch64::XZR, /*IsKill=*/true);
3689 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3690 unsigned Op1, bool Op1IsKill) {
3691 if (RetVT != MVT::i64)
3694 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3695 Op0, Op0IsKill, Op1, Op1IsKill,
3696 AArch64::XZR, /*IsKill=*/true);
3699 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3700 unsigned Op1Reg, bool Op1IsKill) {
3702 bool NeedTrunc = false;
3704 switch (RetVT.SimpleTy) {
3706 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3707 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3708 case MVT::i32: Opc = AArch64::LSLVWr; break;
3709 case MVT::i64: Opc = AArch64::LSLVXr; break;
3712 const TargetRegisterClass *RC =
3713 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3715 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3718 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3721 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3725 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3726 bool Op0IsKill, uint64_t Shift,
3728 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3729 "Unexpected source/return type pair.");
3730 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3731 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3732 "Unexpected source value type.");
3733 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3734 RetVT == MVT::i64) && "Unexpected return value type.");
3736 bool Is64Bit = (RetVT == MVT::i64);
3737 unsigned RegSize = Is64Bit ? 64 : 32;
3738 unsigned DstBits = RetVT.getSizeInBits();
3739 unsigned SrcBits = SrcVT.getSizeInBits();
3741 // Don't deal with undefined shifts.
3742 if (Shift >= DstBits)
3745 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3746 // {S|U}BFM Wd, Wn, #r, #s
3747 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3749 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3750 // %2 = shl i16 %1, 4
3751 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3752 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3753 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3754 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3756 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3757 // %2 = shl i16 %1, 8
3758 // Wd<32+7-24,32-24> = Wn<7:0>
3759 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3760 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3761 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3763 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3764 // %2 = shl i16 %1, 12
3765 // Wd<32+3-20,32-20> = Wn<3:0>
3766 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3767 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3768 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3770 unsigned ImmR = RegSize - Shift;
3771 // Limit the width to the length of the source type.
3772 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3773 static const unsigned OpcTable[2][2] = {
3774 {AArch64::SBFMWri, AArch64::SBFMXri},
3775 {AArch64::UBFMWri, AArch64::UBFMXri}
3777 unsigned Opc = OpcTable[IsZext][Is64Bit];
3778 const TargetRegisterClass *RC =
3779 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3780 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3781 unsigned TmpReg = MRI.createVirtualRegister(RC);
3782 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3783 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3785 .addReg(Op0, getKillRegState(Op0IsKill))
3786 .addImm(AArch64::sub_32);
3790 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3793 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3794 unsigned Op1Reg, bool Op1IsKill) {
3796 bool NeedTrunc = false;
3798 switch (RetVT.SimpleTy) {
3800 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3801 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3802 case MVT::i32: Opc = AArch64::LSRVWr; break;
3803 case MVT::i64: Opc = AArch64::LSRVXr; break;
3806 const TargetRegisterClass *RC =
3807 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3809 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3810 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3811 Op0IsKill = Op1IsKill = true;
3813 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3816 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3820 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3821 bool Op0IsKill, uint64_t Shift,
3823 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3824 "Unexpected source/return type pair.");
3825 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3826 SrcVT == MVT::i64) && "Unexpected source value type.");
3827 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3828 RetVT == MVT::i64) && "Unexpected return value type.");
3830 bool Is64Bit = (RetVT == MVT::i64);
3831 unsigned RegSize = Is64Bit ? 64 : 32;
3832 unsigned DstBits = RetVT.getSizeInBits();
3833 unsigned SrcBits = SrcVT.getSizeInBits();
3835 // Don't deal with undefined shifts.
3836 if (Shift >= DstBits)
3839 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3840 // {S|U}BFM Wd, Wn, #r, #s
3841 // Wd<s-r:0> = Wn<s:r> when r <= s
3843 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3844 // %2 = lshr i16 %1, 4
3845 // Wd<7-4:0> = Wn<7:4>
3846 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3847 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3848 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3850 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3851 // %2 = lshr i16 %1, 8
3852 // Wd<7-7,0> = Wn<7:7>
3853 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3854 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3855 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3857 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3858 // %2 = lshr i16 %1, 12
3859 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3860 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3861 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3862 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3864 if (Shift >= SrcBits && IsZExt)
3865 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3867 // It is not possible to fold a sign-extend into the LShr instruction. In this
3868 // case emit a sign-extend.
3870 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3875 SrcBits = SrcVT.getSizeInBits();
3879 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3880 unsigned ImmS = SrcBits - 1;
3881 static const unsigned OpcTable[2][2] = {
3882 {AArch64::SBFMWri, AArch64::SBFMXri},
3883 {AArch64::UBFMWri, AArch64::UBFMXri}
3885 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3886 const TargetRegisterClass *RC =
3887 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3888 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3889 unsigned TmpReg = MRI.createVirtualRegister(RC);
3890 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3891 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3893 .addReg(Op0, getKillRegState(Op0IsKill))
3894 .addImm(AArch64::sub_32);
3898 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3901 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3902 unsigned Op1Reg, bool Op1IsKill) {
3904 bool NeedTrunc = false;
3906 switch (RetVT.SimpleTy) {
3908 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
3909 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3910 case MVT::i32: Opc = AArch64::ASRVWr; break;
3911 case MVT::i64: Opc = AArch64::ASRVXr; break;
3914 const TargetRegisterClass *RC =
3915 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3917 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3918 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3919 Op0IsKill = Op1IsKill = true;
3921 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3924 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3928 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3929 bool Op0IsKill, uint64_t Shift,
3931 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3932 "Unexpected source/return type pair.");
3933 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3934 SrcVT == MVT::i64) && "Unexpected source value type.");
3935 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3936 RetVT == MVT::i64) && "Unexpected return value type.");
3938 bool Is64Bit = (RetVT == MVT::i64);
3939 unsigned RegSize = Is64Bit ? 64 : 32;
3940 unsigned DstBits = RetVT.getSizeInBits();
3941 unsigned SrcBits = SrcVT.getSizeInBits();
3943 // Don't deal with undefined shifts.
3944 if (Shift >= DstBits)
3947 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3948 // {S|U}BFM Wd, Wn, #r, #s
3949 // Wd<s-r:0> = Wn<s:r> when r <= s
3951 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3952 // %2 = ashr i16 %1, 4
3953 // Wd<7-4:0> = Wn<7:4>
3954 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
3955 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3956 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3958 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3959 // %2 = ashr i16 %1, 8
3960 // Wd<7-7,0> = Wn<7:7>
3961 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3962 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3963 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3965 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3966 // %2 = ashr i16 %1, 12
3967 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3968 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
3969 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3970 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3972 if (Shift >= SrcBits && IsZExt)
3973 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3975 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3976 unsigned ImmS = SrcBits - 1;
3977 static const unsigned OpcTable[2][2] = {
3978 {AArch64::SBFMWri, AArch64::SBFMXri},
3979 {AArch64::UBFMWri, AArch64::UBFMXri}
3981 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3982 const TargetRegisterClass *RC =
3983 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3984 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3985 unsigned TmpReg = MRI.createVirtualRegister(RC);
3986 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3987 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3989 .addReg(Op0, getKillRegState(Op0IsKill))
3990 .addImm(AArch64::sub_32);
3994 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3997 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
3999 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4001 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4002 // DestVT are odd things, so test to make sure that they are both types we can
4003 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4004 // bail out to SelectionDAG.
4005 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4006 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4007 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4008 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4014 switch (SrcVT.SimpleTy) {
4018 return emiti1Ext(SrcReg, DestVT, IsZExt);
4020 if (DestVT == MVT::i64)
4021 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4023 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4027 if (DestVT == MVT::i64)
4028 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4030 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4034 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4035 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4040 // Handle i8 and i16 as i32.
4041 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4043 else if (DestVT == MVT::i64) {
4044 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4045 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4046 TII.get(AArch64::SUBREG_TO_REG), Src64)
4049 .addImm(AArch64::sub_32);
4053 const TargetRegisterClass *RC =
4054 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4055 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4058 static bool isZExtLoad(const MachineInstr *LI) {
4059 switch (LI->getOpcode()) {
4062 case AArch64::LDURBBi:
4063 case AArch64::LDURHHi:
4064 case AArch64::LDURWi:
4065 case AArch64::LDRBBui:
4066 case AArch64::LDRHHui:
4067 case AArch64::LDRWui:
4068 case AArch64::LDRBBroX:
4069 case AArch64::LDRHHroX:
4070 case AArch64::LDRWroX:
4071 case AArch64::LDRBBroW:
4072 case AArch64::LDRHHroW:
4073 case AArch64::LDRWroW:
4078 static bool isSExtLoad(const MachineInstr *LI) {
4079 switch (LI->getOpcode()) {
4082 case AArch64::LDURSBWi:
4083 case AArch64::LDURSHWi:
4084 case AArch64::LDURSBXi:
4085 case AArch64::LDURSHXi:
4086 case AArch64::LDURSWi:
4087 case AArch64::LDRSBWui:
4088 case AArch64::LDRSHWui:
4089 case AArch64::LDRSBXui:
4090 case AArch64::LDRSHXui:
4091 case AArch64::LDRSWui:
4092 case AArch64::LDRSBWroX:
4093 case AArch64::LDRSHWroX:
4094 case AArch64::LDRSBXroX:
4095 case AArch64::LDRSHXroX:
4096 case AArch64::LDRSWroX:
4097 case AArch64::LDRSBWroW:
4098 case AArch64::LDRSHWroW:
4099 case AArch64::LDRSBXroW:
4100 case AArch64::LDRSHXroW:
4101 case AArch64::LDRSWroW:
4106 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4108 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4109 if (!LI || !LI->hasOneUse())
4112 // Check if the load instruction has already been selected.
4113 unsigned Reg = lookUpRegForValue(LI);
4117 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4121 // Check if the correct load instruction has been emitted - SelectionDAG might
4122 // have emitted a zero-extending load, but we need a sign-extending load.
4123 bool IsZExt = isa<ZExtInst>(I);
4124 const auto *LoadMI = MI;
4125 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4126 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4127 unsigned LoadReg = MI->getOperand(1).getReg();
4128 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4129 assert(LoadMI && "Expected valid instruction");
4131 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4134 // Nothing to be done.
4135 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4136 updateValueMap(I, Reg);
4141 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4142 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4143 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4145 .addReg(Reg, getKillRegState(true))
4146 .addImm(AArch64::sub_32);
4149 assert((MI->getOpcode() == TargetOpcode::COPY &&
4150 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4151 "Expected copy instruction");
4152 Reg = MI->getOperand(1).getReg();
4153 MI->eraseFromParent();
4155 updateValueMap(I, Reg);
4159 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4160 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4161 "Unexpected integer extend instruction.");
4164 if (!isTypeSupported(I->getType(), RetVT))
4167 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4170 // Try to optimize already sign-/zero-extended values from load instructions.
4171 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4174 unsigned SrcReg = getRegForValue(I->getOperand(0));
4177 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4179 // Try to optimize already sign-/zero-extended values from function arguments.
4180 bool IsZExt = isa<ZExtInst>(I);
4181 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4182 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4183 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4184 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4185 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4186 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4188 .addReg(SrcReg, getKillRegState(SrcIsKill))
4189 .addImm(AArch64::sub_32);
4192 updateValueMap(I, SrcReg);
4197 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4201 updateValueMap(I, ResultReg);
4205 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4206 EVT DestEVT = TLI.getValueType(I->getType(), true);
4207 if (!DestEVT.isSimple())
4210 MVT DestVT = DestEVT.getSimpleVT();
4211 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4215 bool Is64bit = (DestVT == MVT::i64);
4216 switch (ISDOpcode) {
4220 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4223 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4226 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4227 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4230 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4232 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4235 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4237 const TargetRegisterClass *RC =
4238 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4239 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4240 Src1Reg, /*IsKill=*/false);
4241 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4242 // The remainder is computed as numerator - (quotient * denominator) using the
4243 // MSUB instruction.
4244 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4245 Src1Reg, Src1IsKill, Src0Reg,
4247 updateValueMap(I, ResultReg);
4251 bool AArch64FastISel::selectMul(const Instruction *I) {
4253 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4257 return selectBinaryOp(I, ISD::MUL);
4259 const Value *Src0 = I->getOperand(0);
4260 const Value *Src1 = I->getOperand(1);
4261 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4262 if (C->getValue().isPowerOf2())
4263 std::swap(Src0, Src1);
4265 // Try to simplify to a shift instruction.
4266 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4267 if (C->getValue().isPowerOf2()) {
4268 uint64_t ShiftVal = C->getValue().logBase2();
4271 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4272 if (!isIntExtFree(ZExt)) {
4274 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4277 Src0 = ZExt->getOperand(0);
4280 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4281 if (!isIntExtFree(SExt)) {
4283 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4286 Src0 = SExt->getOperand(0);
4291 unsigned Src0Reg = getRegForValue(Src0);
4294 bool Src0IsKill = hasTrivialKill(Src0);
4296 unsigned ResultReg =
4297 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4300 updateValueMap(I, ResultReg);
4305 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4308 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4310 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4313 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4315 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4320 updateValueMap(I, ResultReg);
4324 bool AArch64FastISel::selectShift(const Instruction *I) {
4326 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4329 if (RetVT.isVector())
4330 return selectOperator(I, I->getOpcode());
4332 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4333 unsigned ResultReg = 0;
4334 uint64_t ShiftVal = C->getZExtValue();
4336 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4337 const Value *Op0 = I->getOperand(0);
4338 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4339 if (!isIntExtFree(ZExt)) {
4341 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4344 Op0 = ZExt->getOperand(0);
4347 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4348 if (!isIntExtFree(SExt)) {
4350 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4353 Op0 = SExt->getOperand(0);
4358 unsigned Op0Reg = getRegForValue(Op0);
4361 bool Op0IsKill = hasTrivialKill(Op0);
4363 switch (I->getOpcode()) {
4364 default: llvm_unreachable("Unexpected instruction.");
4365 case Instruction::Shl:
4366 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4368 case Instruction::AShr:
4369 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4371 case Instruction::LShr:
4372 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4378 updateValueMap(I, ResultReg);
4382 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4385 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4387 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4390 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4392 unsigned ResultReg = 0;
4393 switch (I->getOpcode()) {
4394 default: llvm_unreachable("Unexpected instruction.");
4395 case Instruction::Shl:
4396 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4398 case Instruction::AShr:
4399 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4401 case Instruction::LShr:
4402 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4409 updateValueMap(I, ResultReg);
4413 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4416 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4418 if (!isTypeLegal(I->getType(), RetVT))
4422 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4423 Opc = AArch64::FMOVWSr;
4424 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4425 Opc = AArch64::FMOVXDr;
4426 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4427 Opc = AArch64::FMOVSWr;
4428 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4429 Opc = AArch64::FMOVDXr;
4433 const TargetRegisterClass *RC = nullptr;
4434 switch (RetVT.SimpleTy) {
4435 default: llvm_unreachable("Unexpected value type.");
4436 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4437 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4438 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4439 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4441 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4444 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4445 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4450 updateValueMap(I, ResultReg);
4454 bool AArch64FastISel::selectFRem(const Instruction *I) {
4456 if (!isTypeLegal(I->getType(), RetVT))
4460 switch (RetVT.SimpleTy) {
4464 LC = RTLIB::REM_F32;
4467 LC = RTLIB::REM_F64;
4472 Args.reserve(I->getNumOperands());
4474 // Populate the argument list.
4475 for (auto &Arg : I->operands()) {
4478 Entry.Ty = Arg->getType();
4479 Args.push_back(Entry);
4482 CallLoweringInfo CLI;
4483 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4484 TLI.getLibcallName(LC), std::move(Args));
4485 if (!lowerCallTo(CLI))
4487 updateValueMap(I, CLI.ResultReg);
4491 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4493 if (!isTypeLegal(I->getType(), VT))
4496 if (!isa<ConstantInt>(I->getOperand(1)))
4497 return selectBinaryOp(I, ISD::SDIV);
4499 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4500 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4501 !(C.isPowerOf2() || (-C).isPowerOf2()))
4502 return selectBinaryOp(I, ISD::SDIV);
4504 unsigned Lg2 = C.countTrailingZeros();
4505 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4508 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4510 if (cast<BinaryOperator>(I)->isExact()) {
4511 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4514 updateValueMap(I, ResultReg);
4518 unsigned Pow2MinusOne = (1 << Lg2) - 1;
4519 unsigned AddReg = emitAddSub_ri(/*UseAdd=*/true, VT, Src0Reg,
4520 /*IsKill=*/false, Pow2MinusOne);
4524 // (Src0 < 0) ? Pow2 - 1 : 0;
4525 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4529 const TargetRegisterClass *RC;
4530 if (VT == MVT::i64) {
4531 SelectOpc = AArch64::CSELXr;
4532 RC = &AArch64::GPR64RegClass;
4534 SelectOpc = AArch64::CSELWr;
4535 RC = &AArch64::GPR32RegClass;
4537 unsigned SelectReg =
4538 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4539 Src0IsKill, AArch64CC::LT);
4543 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4544 // negate the result.
4545 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4548 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4549 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4551 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4556 updateValueMap(I, ResultReg);
4560 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4561 /// duplicate it for AArch64, because otherwise we would bail out even for
4562 /// simple cases. This is because the standard fastEmit functions don't cover
4563 /// MUL at all and ADD is lowered very inefficientily.
4564 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4565 unsigned N = getRegForValue(I->getOperand(0));
4568 bool NIsKill = hasTrivialKill(I->getOperand(0));
4570 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4571 // into a single N = N + TotalOffset.
4572 uint64_t TotalOffs = 0;
4573 Type *Ty = I->getOperand(0)->getType();
4574 MVT VT = TLI.getPointerTy();
4575 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4576 const Value *Idx = *OI;
4577 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4578 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4581 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4582 Ty = StTy->getElementType(Field);
4584 Ty = cast<SequentialType>(Ty)->getElementType();
4585 // If this is a constant subscript, handle it quickly.
4586 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4591 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4595 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4602 // N = N + Idx * ElementSize;
4603 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4604 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4605 unsigned IdxN = Pair.first;
4606 bool IdxNIsKill = Pair.second;
4610 if (ElementSize != 1) {
4611 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4614 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4619 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4625 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4629 updateValueMap(I, N);
4633 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4634 switch (I->getOpcode()) {
4637 case Instruction::Add:
4638 case Instruction::Sub:
4639 return selectAddSub(I);
4640 case Instruction::Mul:
4641 return selectMul(I);
4642 case Instruction::SDiv:
4643 return selectSDiv(I);
4644 case Instruction::SRem:
4645 if (!selectBinaryOp(I, ISD::SREM))
4646 return selectRem(I, ISD::SREM);
4648 case Instruction::URem:
4649 if (!selectBinaryOp(I, ISD::UREM))
4650 return selectRem(I, ISD::UREM);
4652 case Instruction::Shl:
4653 case Instruction::LShr:
4654 case Instruction::AShr:
4655 return selectShift(I);
4656 case Instruction::And:
4657 case Instruction::Or:
4658 case Instruction::Xor:
4659 return selectLogicalOp(I);
4660 case Instruction::Br:
4661 return selectBranch(I);
4662 case Instruction::IndirectBr:
4663 return selectIndirectBr(I);
4664 case Instruction::BitCast:
4665 if (!FastISel::selectBitCast(I))
4666 return selectBitCast(I);
4668 case Instruction::FPToSI:
4669 if (!selectCast(I, ISD::FP_TO_SINT))
4670 return selectFPToInt(I, /*Signed=*/true);
4672 case Instruction::FPToUI:
4673 return selectFPToInt(I, /*Signed=*/false);
4674 case Instruction::ZExt:
4675 case Instruction::SExt:
4676 return selectIntExt(I);
4677 case Instruction::Trunc:
4678 if (!selectCast(I, ISD::TRUNCATE))
4679 return selectTrunc(I);
4681 case Instruction::FPExt:
4682 return selectFPExt(I);
4683 case Instruction::FPTrunc:
4684 return selectFPTrunc(I);
4685 case Instruction::SIToFP:
4686 if (!selectCast(I, ISD::SINT_TO_FP))
4687 return selectIntToFP(I, /*Signed=*/true);
4689 case Instruction::UIToFP:
4690 return selectIntToFP(I, /*Signed=*/false);
4691 case Instruction::Load:
4692 return selectLoad(I);
4693 case Instruction::Store:
4694 return selectStore(I);
4695 case Instruction::FCmp:
4696 case Instruction::ICmp:
4697 return selectCmp(I);
4698 case Instruction::Select:
4699 return selectSelect(I);
4700 case Instruction::Ret:
4701 return selectRet(I);
4702 case Instruction::FRem:
4703 return selectFRem(I);
4704 case Instruction::GetElementPtr:
4705 return selectGetElementPtr(I);
4708 // fall-back to target-independent instruction selection.
4709 return selectOperator(I, I->getOpcode());
4710 // Silence warnings.
4711 (void)&CC_AArch64_DarwinPCS_VarArg;
4715 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4716 const TargetLibraryInfo *LibInfo) {
4717 return new AArch64FastISel(FuncInfo, LibInfo);