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) {
83 unsigned getOffsetReg() const {
86 void setFI(unsigned FI) {
87 assert(isFIBase() && "Invalid base frame index access!");
90 unsigned getFI() const {
91 assert(isFIBase() && "Invalid base frame index access!");
94 void setOffset(int64_t O) { Offset = O; }
95 int64_t getOffset() { return Offset; }
96 void setShift(unsigned S) { Shift = S; }
97 unsigned getShift() { return Shift; }
99 void setGlobalValue(const GlobalValue *G) { GV = G; }
100 const GlobalValue *getGlobalValue() { return GV; }
103 /// Subtarget - Keep a pointer to the AArch64Subtarget around so that we can
104 /// make the right decision when generating code for different targets.
105 const AArch64Subtarget *Subtarget;
106 LLVMContext *Context;
108 bool fastLowerArguments() override;
109 bool fastLowerCall(CallLoweringInfo &CLI) override;
110 bool fastLowerIntrinsicCall(const IntrinsicInst *II) override;
113 // Selection routines.
114 bool selectAddSub(const Instruction *I);
115 bool selectLogicalOp(const Instruction *I);
116 bool selectLoad(const Instruction *I);
117 bool selectStore(const Instruction *I);
118 bool selectBranch(const Instruction *I);
119 bool selectIndirectBr(const Instruction *I);
120 bool selectCmp(const Instruction *I);
121 bool selectSelect(const Instruction *I);
122 bool selectFPExt(const Instruction *I);
123 bool selectFPTrunc(const Instruction *I);
124 bool selectFPToInt(const Instruction *I, bool Signed);
125 bool selectIntToFP(const Instruction *I, bool Signed);
126 bool selectRem(const Instruction *I, unsigned ISDOpcode);
127 bool selectRet(const Instruction *I);
128 bool selectTrunc(const Instruction *I);
129 bool selectIntExt(const Instruction *I);
130 bool selectMul(const Instruction *I);
131 bool selectShift(const Instruction *I);
132 bool selectBitCast(const Instruction *I);
133 bool selectFRem(const Instruction *I);
134 bool selectSDiv(const Instruction *I);
135 bool selectGetElementPtr(const Instruction *I);
137 // Utility helper routines.
138 bool isTypeLegal(Type *Ty, MVT &VT);
139 bool isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed = false);
140 bool isValueAvailable(const Value *V) const;
141 bool computeAddress(const Value *Obj, Address &Addr, Type *Ty = nullptr);
142 bool computeCallAddress(const Value *V, Address &Addr);
143 bool simplifyAddress(Address &Addr, MVT VT);
144 void addLoadStoreOperands(Address &Addr, const MachineInstrBuilder &MIB,
145 unsigned Flags, unsigned ScaleFactor,
146 MachineMemOperand *MMO);
147 bool isMemCpySmall(uint64_t Len, unsigned Alignment);
148 bool tryEmitSmallMemCpy(Address Dest, Address Src, uint64_t Len,
150 bool foldXALUIntrinsic(AArch64CC::CondCode &CC, const Instruction *I,
152 bool optimizeIntExtLoad(const Instruction *I, MVT RetVT, MVT SrcVT);
154 // Emit helper routines.
155 unsigned emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
156 const Value *RHS, bool SetFlags = false,
157 bool WantResult = true, bool IsZExt = false);
158 unsigned emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
159 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
160 bool SetFlags = false, bool WantResult = true);
161 unsigned emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
162 bool LHSIsKill, uint64_t Imm, bool SetFlags = false,
163 bool WantResult = true);
164 unsigned emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
165 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
166 AArch64_AM::ShiftExtendType ShiftType,
167 uint64_t ShiftImm, bool SetFlags = false,
168 bool WantResult = true);
169 unsigned emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
170 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
171 AArch64_AM::ShiftExtendType ExtType,
172 uint64_t ShiftImm, bool SetFlags = false,
173 bool WantResult = true);
176 bool emitCompareAndBranch(const BranchInst *BI);
177 bool emitCmp(const Value *LHS, const Value *RHS, bool IsZExt);
178 bool emitICmp(MVT RetVT, const Value *LHS, const Value *RHS, bool IsZExt);
179 bool emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
180 bool emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS);
181 unsigned emitLoad(MVT VT, MVT ResultVT, Address Addr, bool WantZExt = true,
182 MachineMemOperand *MMO = nullptr);
183 bool emitStore(MVT VT, unsigned SrcReg, Address Addr,
184 MachineMemOperand *MMO = nullptr);
185 unsigned emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT, bool isZExt);
186 unsigned emiti1Ext(unsigned SrcReg, MVT DestVT, bool isZExt);
187 unsigned emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
188 bool SetFlags = false, bool WantResult = true,
189 bool IsZExt = false);
190 unsigned emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill, int64_t Imm);
191 unsigned emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
192 bool SetFlags = false, bool WantResult = true,
193 bool IsZExt = false);
194 unsigned emitSubs_rr(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
195 unsigned RHSReg, bool RHSIsKill, bool WantResult = true);
196 unsigned emitSubs_rs(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
197 unsigned RHSReg, bool RHSIsKill,
198 AArch64_AM::ShiftExtendType ShiftType, uint64_t ShiftImm,
199 bool WantResult = true);
200 unsigned emitLogicalOp(unsigned ISDOpc, MVT RetVT, const Value *LHS,
202 unsigned emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
203 bool LHSIsKill, uint64_t Imm);
204 unsigned emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT, unsigned LHSReg,
205 bool LHSIsKill, unsigned RHSReg, bool RHSIsKill,
207 unsigned emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill, uint64_t Imm);
208 unsigned emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
209 unsigned Op1, bool Op1IsKill);
210 unsigned emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
211 unsigned Op1, bool Op1IsKill);
212 unsigned emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
213 unsigned Op1, bool Op1IsKill);
214 unsigned emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
215 unsigned Op1Reg, bool Op1IsKill);
216 unsigned emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
217 uint64_t Imm, bool IsZExt = true);
218 unsigned emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
219 unsigned Op1Reg, bool Op1IsKill);
220 unsigned emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
221 uint64_t Imm, bool IsZExt = true);
222 unsigned emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
223 unsigned Op1Reg, bool Op1IsKill);
224 unsigned emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0Reg, bool Op0IsKill,
225 uint64_t Imm, bool IsZExt = false);
227 unsigned materializeInt(const ConstantInt *CI, MVT VT);
228 unsigned materializeFP(const ConstantFP *CFP, MVT VT);
229 unsigned materializeGV(const GlobalValue *GV);
231 // Call handling routines.
233 CCAssignFn *CCAssignFnForCall(CallingConv::ID CC) const;
234 bool processCallArgs(CallLoweringInfo &CLI, SmallVectorImpl<MVT> &ArgVTs,
236 bool finishCall(CallLoweringInfo &CLI, MVT RetVT, unsigned NumBytes);
239 // Backend specific FastISel code.
240 unsigned fastMaterializeAlloca(const AllocaInst *AI) override;
241 unsigned fastMaterializeConstant(const Constant *C) override;
242 unsigned fastMaterializeFloatZero(const ConstantFP* CF) override;
244 explicit AArch64FastISel(FunctionLoweringInfo &FuncInfo,
245 const TargetLibraryInfo *LibInfo)
246 : FastISel(FuncInfo, LibInfo, /*SkipTargetIndependentISel=*/true) {
247 Subtarget = &TM.getSubtarget<AArch64Subtarget>();
248 Context = &FuncInfo.Fn->getContext();
251 bool fastSelectInstruction(const Instruction *I) override;
253 #include "AArch64GenFastISel.inc"
256 } // end anonymous namespace
258 #include "AArch64GenCallingConv.inc"
260 /// \brief Check if the sign-/zero-extend will be a noop.
261 static bool isIntExtFree(const Instruction *I) {
262 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
263 "Unexpected integer extend instruction.");
264 assert(!I->getType()->isVectorTy() && I->getType()->isIntegerTy() &&
265 "Unexpected value type.");
266 bool IsZExt = isa<ZExtInst>(I);
268 if (const auto *LI = dyn_cast<LoadInst>(I->getOperand(0)))
272 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0)))
273 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr()))
279 /// \brief Determine the implicit scale factor that is applied by a memory
280 /// operation for a given value type.
281 static unsigned getImplicitScaleFactor(MVT VT) {
282 switch (VT.SimpleTy) {
285 case MVT::i1: // fall-through
290 case MVT::i32: // fall-through
293 case MVT::i64: // fall-through
299 CCAssignFn *AArch64FastISel::CCAssignFnForCall(CallingConv::ID CC) const {
300 if (CC == CallingConv::WebKit_JS)
301 return CC_AArch64_WebKit_JS;
302 return Subtarget->isTargetDarwin() ? CC_AArch64_DarwinPCS : CC_AArch64_AAPCS;
305 unsigned AArch64FastISel::fastMaterializeAlloca(const AllocaInst *AI) {
306 assert(TLI.getValueType(AI->getType(), true) == MVT::i64 &&
307 "Alloca should always return a pointer.");
309 // Don't handle dynamic allocas.
310 if (!FuncInfo.StaticAllocaMap.count(AI))
313 DenseMap<const AllocaInst *, int>::iterator SI =
314 FuncInfo.StaticAllocaMap.find(AI);
316 if (SI != FuncInfo.StaticAllocaMap.end()) {
317 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
318 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
320 .addFrameIndex(SI->second)
329 unsigned AArch64FastISel::materializeInt(const ConstantInt *CI, MVT VT) {
334 return fastEmit_i(VT, VT, ISD::Constant, CI->getZExtValue());
336 // Create a copy from the zero register to materialize a "0" value.
337 const TargetRegisterClass *RC = (VT == MVT::i64) ? &AArch64::GPR64RegClass
338 : &AArch64::GPR32RegClass;
339 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
340 unsigned ResultReg = createResultReg(RC);
341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(TargetOpcode::COPY),
342 ResultReg).addReg(ZeroReg, getKillRegState(true));
346 unsigned AArch64FastISel::materializeFP(const ConstantFP *CFP, MVT VT) {
347 // Positive zero (+0.0) has to be materialized with a fmov from the zero
348 // register, because the immediate version of fmov cannot encode zero.
349 if (CFP->isNullValue())
350 return fastMaterializeFloatZero(CFP);
352 if (VT != MVT::f32 && VT != MVT::f64)
355 const APFloat Val = CFP->getValueAPF();
356 bool Is64Bit = (VT == MVT::f64);
357 // This checks to see if we can use FMOV instructions to materialize
358 // a constant, otherwise we have to materialize via the constant pool.
359 if (TLI.isFPImmLegal(Val, VT)) {
361 Is64Bit ? AArch64_AM::getFP64Imm(Val) : AArch64_AM::getFP32Imm(Val);
362 assert((Imm != -1) && "Cannot encode floating-point constant.");
363 unsigned Opc = Is64Bit ? AArch64::FMOVDi : AArch64::FMOVSi;
364 return fastEmitInst_i(Opc, TLI.getRegClassFor(VT), Imm);
367 // Materialize via constant pool. MachineConstantPool wants an explicit
369 unsigned Align = DL.getPrefTypeAlignment(CFP->getType());
371 Align = DL.getTypeAllocSize(CFP->getType());
373 unsigned CPI = MCP.getConstantPoolIndex(cast<Constant>(CFP), Align);
374 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
375 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
376 ADRPReg).addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGE);
378 unsigned Opc = Is64Bit ? AArch64::LDRDui : AArch64::LDRSui;
379 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
380 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
382 .addConstantPoolIndex(CPI, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
386 unsigned AArch64FastISel::materializeGV(const GlobalValue *GV) {
387 // We can't handle thread-local variables quickly yet.
388 if (GV->isThreadLocal())
391 // MachO still uses GOT for large code-model accesses, but ELF requires
392 // movz/movk sequences, which FastISel doesn't handle yet.
393 if (TM.getCodeModel() != CodeModel::Small && !Subtarget->isTargetMachO())
396 unsigned char OpFlags = Subtarget->ClassifyGlobalReference(GV, TM);
398 EVT DestEVT = TLI.getValueType(GV->getType(), true);
399 if (!DestEVT.isSimple())
402 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
405 if (OpFlags & AArch64II::MO_GOT) {
407 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
409 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGE);
411 ResultReg = createResultReg(&AArch64::GPR64RegClass);
412 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
415 .addGlobalAddress(GV, 0, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
417 } else if (OpFlags & AArch64II::MO_CONSTPOOL) {
418 // We can't handle addresses loaded from a constant pool quickly yet.
422 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
424 .addGlobalAddress(GV, 0, AArch64II::MO_PAGE);
426 ResultReg = createResultReg(&AArch64::GPR64spRegClass);
427 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
430 .addGlobalAddress(GV, 0, AArch64II::MO_PAGEOFF | AArch64II::MO_NC)
436 unsigned AArch64FastISel::fastMaterializeConstant(const Constant *C) {
437 EVT CEVT = TLI.getValueType(C->getType(), true);
439 // Only handle simple types.
440 if (!CEVT.isSimple())
442 MVT VT = CEVT.getSimpleVT();
444 if (const auto *CI = dyn_cast<ConstantInt>(C))
445 return materializeInt(CI, VT);
446 else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(C))
447 return materializeFP(CFP, VT);
448 else if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
449 return materializeGV(GV);
454 unsigned AArch64FastISel::fastMaterializeFloatZero(const ConstantFP* CFP) {
455 assert(CFP->isNullValue() &&
456 "Floating-point constant is not a positive zero.");
458 if (!isTypeLegal(CFP->getType(), VT))
461 if (VT != MVT::f32 && VT != MVT::f64)
464 bool Is64Bit = (VT == MVT::f64);
465 unsigned ZReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
466 unsigned Opc = Is64Bit ? AArch64::FMOVXDr : AArch64::FMOVWSr;
467 return fastEmitInst_r(Opc, TLI.getRegClassFor(VT), ZReg, /*IsKill=*/true);
470 /// \brief Check if the multiply is by a power-of-2 constant.
471 static bool isMulPowOf2(const Value *I) {
472 if (const auto *MI = dyn_cast<MulOperator>(I)) {
473 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(0)))
474 if (C->getValue().isPowerOf2())
476 if (const auto *C = dyn_cast<ConstantInt>(MI->getOperand(1)))
477 if (C->getValue().isPowerOf2())
483 // Computes the address to get to an object.
484 bool AArch64FastISel::computeAddress(const Value *Obj, Address &Addr, Type *Ty)
486 const User *U = nullptr;
487 unsigned Opcode = Instruction::UserOp1;
488 if (const Instruction *I = dyn_cast<Instruction>(Obj)) {
489 // Don't walk into other basic blocks unless the object is an alloca from
490 // another block, otherwise it may not have a virtual register assigned.
491 if (FuncInfo.StaticAllocaMap.count(static_cast<const AllocaInst *>(Obj)) ||
492 FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB) {
493 Opcode = I->getOpcode();
496 } else if (const ConstantExpr *C = dyn_cast<ConstantExpr>(Obj)) {
497 Opcode = C->getOpcode();
501 if (const PointerType *Ty = dyn_cast<PointerType>(Obj->getType()))
502 if (Ty->getAddressSpace() > 255)
503 // Fast instruction selection doesn't support the special
510 case Instruction::BitCast: {
511 // Look through bitcasts.
512 return computeAddress(U->getOperand(0), Addr, Ty);
514 case Instruction::IntToPtr: {
515 // Look past no-op inttoptrs.
516 if (TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
517 return computeAddress(U->getOperand(0), Addr, Ty);
520 case Instruction::PtrToInt: {
521 // Look past no-op ptrtoints.
522 if (TLI.getValueType(U->getType()) == TLI.getPointerTy())
523 return computeAddress(U->getOperand(0), Addr, Ty);
526 case Instruction::GetElementPtr: {
527 Address SavedAddr = Addr;
528 uint64_t TmpOffset = Addr.getOffset();
530 // Iterate through the GEP folding the constants into offsets where
532 gep_type_iterator GTI = gep_type_begin(U);
533 for (User::const_op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e;
535 const Value *Op = *i;
536 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
537 const StructLayout *SL = DL.getStructLayout(STy);
538 unsigned Idx = cast<ConstantInt>(Op)->getZExtValue();
539 TmpOffset += SL->getElementOffset(Idx);
541 uint64_t S = DL.getTypeAllocSize(GTI.getIndexedType());
543 if (const ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
544 // Constant-offset addressing.
545 TmpOffset += CI->getSExtValue() * S;
548 if (canFoldAddIntoGEP(U, Op)) {
549 // A compatible add with a constant operand. Fold the constant.
551 cast<ConstantInt>(cast<AddOperator>(Op)->getOperand(1));
552 TmpOffset += CI->getSExtValue() * S;
553 // Iterate on the other operand.
554 Op = cast<AddOperator>(Op)->getOperand(0);
558 goto unsupported_gep;
563 // Try to grab the base operand now.
564 Addr.setOffset(TmpOffset);
565 if (computeAddress(U->getOperand(0), Addr, Ty))
568 // We failed, restore everything and try the other options.
574 case Instruction::Alloca: {
575 const AllocaInst *AI = cast<AllocaInst>(Obj);
576 DenseMap<const AllocaInst *, int>::iterator SI =
577 FuncInfo.StaticAllocaMap.find(AI);
578 if (SI != FuncInfo.StaticAllocaMap.end()) {
579 Addr.setKind(Address::FrameIndexBase);
580 Addr.setFI(SI->second);
585 case Instruction::Add: {
586 // Adds of constants are common and easy enough.
587 const Value *LHS = U->getOperand(0);
588 const Value *RHS = U->getOperand(1);
590 if (isa<ConstantInt>(LHS))
593 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
594 Addr.setOffset(Addr.getOffset() + CI->getSExtValue());
595 return computeAddress(LHS, Addr, Ty);
598 Address Backup = Addr;
599 if (computeAddress(LHS, Addr, Ty) && computeAddress(RHS, Addr, Ty))
605 case Instruction::Sub: {
606 // Subs of constants are common and easy enough.
607 const Value *LHS = U->getOperand(0);
608 const Value *RHS = U->getOperand(1);
610 if (const ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
611 Addr.setOffset(Addr.getOffset() - CI->getSExtValue());
612 return computeAddress(LHS, Addr, Ty);
616 case Instruction::Shl: {
617 if (Addr.getOffsetReg())
620 const auto *CI = dyn_cast<ConstantInt>(U->getOperand(1));
624 unsigned Val = CI->getZExtValue();
625 if (Val < 1 || Val > 3)
628 uint64_t NumBytes = 0;
629 if (Ty && Ty->isSized()) {
630 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
631 NumBytes = NumBits / 8;
632 if (!isPowerOf2_64(NumBits))
636 if (NumBytes != (1ULL << Val))
640 Addr.setExtendType(AArch64_AM::LSL);
642 const Value *Src = U->getOperand(0);
643 if (const auto *I = dyn_cast<Instruction>(Src))
644 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
647 // Fold the zext or sext when it won't become a noop.
648 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
649 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
650 Addr.setExtendType(AArch64_AM::UXTW);
651 Src = ZE->getOperand(0);
653 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
654 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
655 Addr.setExtendType(AArch64_AM::SXTW);
656 Src = SE->getOperand(0);
660 if (const auto *AI = dyn_cast<BinaryOperator>(Src))
661 if (AI->getOpcode() == Instruction::And) {
662 const Value *LHS = AI->getOperand(0);
663 const Value *RHS = AI->getOperand(1);
665 if (const auto *C = dyn_cast<ConstantInt>(LHS))
666 if (C->getValue() == 0xffffffff)
669 if (const auto *C = dyn_cast<ConstantInt>(RHS))
670 if (C->getValue() == 0xffffffff) {
671 Addr.setExtendType(AArch64_AM::UXTW);
672 unsigned Reg = getRegForValue(LHS);
675 bool RegIsKill = hasTrivialKill(LHS);
676 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
678 Addr.setOffsetReg(Reg);
683 unsigned Reg = getRegForValue(Src);
686 Addr.setOffsetReg(Reg);
689 case Instruction::Mul: {
690 if (Addr.getOffsetReg())
696 const Value *LHS = U->getOperand(0);
697 const Value *RHS = U->getOperand(1);
699 // Canonicalize power-of-2 value to the RHS.
700 if (const auto *C = dyn_cast<ConstantInt>(LHS))
701 if (C->getValue().isPowerOf2())
704 assert(isa<ConstantInt>(RHS) && "Expected an ConstantInt.");
705 const auto *C = cast<ConstantInt>(RHS);
706 unsigned Val = C->getValue().logBase2();
707 if (Val < 1 || Val > 3)
710 uint64_t NumBytes = 0;
711 if (Ty && Ty->isSized()) {
712 uint64_t NumBits = DL.getTypeSizeInBits(Ty);
713 NumBytes = NumBits / 8;
714 if (!isPowerOf2_64(NumBits))
718 if (NumBytes != (1ULL << Val))
722 Addr.setExtendType(AArch64_AM::LSL);
724 const Value *Src = LHS;
725 if (const auto *I = dyn_cast<Instruction>(Src))
726 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
730 // Fold the zext or sext when it won't become a noop.
731 if (const auto *ZE = dyn_cast<ZExtInst>(Src)) {
732 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
733 Addr.setExtendType(AArch64_AM::UXTW);
734 Src = ZE->getOperand(0);
736 } else if (const auto *SE = dyn_cast<SExtInst>(Src)) {
737 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
738 Addr.setExtendType(AArch64_AM::SXTW);
739 Src = SE->getOperand(0);
743 unsigned Reg = getRegForValue(Src);
746 Addr.setOffsetReg(Reg);
749 case Instruction::And: {
750 if (Addr.getOffsetReg())
753 if (DL.getTypeSizeInBits(Ty) != 8)
756 const Value *LHS = U->getOperand(0);
757 const Value *RHS = U->getOperand(1);
759 if (const auto *C = dyn_cast<ConstantInt>(LHS))
760 if (C->getValue() == 0xffffffff)
763 if (const auto *C = dyn_cast<ConstantInt>(RHS))
764 if (C->getValue() == 0xffffffff) {
766 Addr.setExtendType(AArch64_AM::LSL);
767 Addr.setExtendType(AArch64_AM::UXTW);
769 unsigned Reg = getRegForValue(LHS);
772 bool RegIsKill = hasTrivialKill(LHS);
773 Reg = fastEmitInst_extractsubreg(MVT::i32, Reg, RegIsKill,
775 Addr.setOffsetReg(Reg);
780 case Instruction::SExt:
781 case Instruction::ZExt: {
782 if (!Addr.getReg() || Addr.getOffsetReg())
785 const Value *Src = nullptr;
786 // Fold the zext or sext when it won't become a noop.
787 if (const auto *ZE = dyn_cast<ZExtInst>(U)) {
788 if (!isIntExtFree(ZE) && ZE->getOperand(0)->getType()->isIntegerTy(32)) {
789 Addr.setExtendType(AArch64_AM::UXTW);
790 Src = ZE->getOperand(0);
792 } else if (const auto *SE = dyn_cast<SExtInst>(U)) {
793 if (!isIntExtFree(SE) && SE->getOperand(0)->getType()->isIntegerTy(32)) {
794 Addr.setExtendType(AArch64_AM::SXTW);
795 Src = SE->getOperand(0);
803 unsigned Reg = getRegForValue(Src);
806 Addr.setOffsetReg(Reg);
811 if (Addr.isRegBase() && !Addr.getReg()) {
812 unsigned Reg = getRegForValue(Obj);
819 if (!Addr.getOffsetReg()) {
820 unsigned Reg = getRegForValue(Obj);
823 Addr.setOffsetReg(Reg);
830 bool AArch64FastISel::computeCallAddress(const Value *V, Address &Addr) {
831 const User *U = nullptr;
832 unsigned Opcode = Instruction::UserOp1;
835 if (const auto *I = dyn_cast<Instruction>(V)) {
836 Opcode = I->getOpcode();
838 InMBB = I->getParent() == FuncInfo.MBB->getBasicBlock();
839 } else if (const auto *C = dyn_cast<ConstantExpr>(V)) {
840 Opcode = C->getOpcode();
846 case Instruction::BitCast:
847 // Look past bitcasts if its operand is in the same BB.
849 return computeCallAddress(U->getOperand(0), Addr);
851 case Instruction::IntToPtr:
852 // Look past no-op inttoptrs if its operand is in the same BB.
854 TLI.getValueType(U->getOperand(0)->getType()) == TLI.getPointerTy())
855 return computeCallAddress(U->getOperand(0), Addr);
857 case Instruction::PtrToInt:
858 // Look past no-op ptrtoints if its operand is in the same BB.
860 TLI.getValueType(U->getType()) == TLI.getPointerTy())
861 return computeCallAddress(U->getOperand(0), Addr);
865 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
866 Addr.setGlobalValue(GV);
870 // If all else fails, try to materialize the value in a register.
871 if (!Addr.getGlobalValue()) {
872 Addr.setReg(getRegForValue(V));
873 return Addr.getReg() != 0;
880 bool AArch64FastISel::isTypeLegal(Type *Ty, MVT &VT) {
881 EVT evt = TLI.getValueType(Ty, true);
883 // Only handle simple types.
884 if (evt == MVT::Other || !evt.isSimple())
886 VT = evt.getSimpleVT();
888 // This is a legal type, but it's not something we handle in fast-isel.
892 // Handle all other legal types, i.e. a register that will directly hold this
894 return TLI.isTypeLegal(VT);
897 /// \brief Determine if the value type is supported by FastISel.
899 /// FastISel for AArch64 can handle more value types than are legal. This adds
900 /// simple value type such as i1, i8, and i16.
901 bool AArch64FastISel::isTypeSupported(Type *Ty, MVT &VT, bool IsVectorAllowed) {
902 if (Ty->isVectorTy() && !IsVectorAllowed)
905 if (isTypeLegal(Ty, VT))
908 // If this is a type than can be sign or zero-extended to a basic operation
909 // go ahead and accept it now.
910 if (VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16)
916 bool AArch64FastISel::isValueAvailable(const Value *V) const {
917 if (!isa<Instruction>(V))
920 const auto *I = cast<Instruction>(V);
921 if (FuncInfo.MBBMap[I->getParent()] == FuncInfo.MBB)
927 bool AArch64FastISel::simplifyAddress(Address &Addr, MVT VT) {
928 unsigned ScaleFactor = getImplicitScaleFactor(VT);
932 bool ImmediateOffsetNeedsLowering = false;
933 bool RegisterOffsetNeedsLowering = false;
934 int64_t Offset = Addr.getOffset();
935 if (((Offset < 0) || (Offset & (ScaleFactor - 1))) && !isInt<9>(Offset))
936 ImmediateOffsetNeedsLowering = true;
937 else if (Offset > 0 && !(Offset & (ScaleFactor - 1)) &&
938 !isUInt<12>(Offset / ScaleFactor))
939 ImmediateOffsetNeedsLowering = true;
941 // Cannot encode an offset register and an immediate offset in the same
942 // instruction. Fold the immediate offset into the load/store instruction and
943 // emit an additonal add to take care of the offset register.
944 if (!ImmediateOffsetNeedsLowering && Addr.getOffset() && Addr.getOffsetReg())
945 RegisterOffsetNeedsLowering = true;
947 // Cannot encode zero register as base.
948 if (Addr.isRegBase() && Addr.getOffsetReg() && !Addr.getReg())
949 RegisterOffsetNeedsLowering = true;
951 // If this is a stack pointer and the offset needs to be simplified then put
952 // the alloca address into a register, set the base type back to register and
953 // continue. This should almost never happen.
954 if ((ImmediateOffsetNeedsLowering || Addr.getOffsetReg()) && Addr.isFIBase())
956 unsigned ResultReg = createResultReg(&AArch64::GPR64spRegClass);
957 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADDXri),
959 .addFrameIndex(Addr.getFI())
962 Addr.setKind(Address::RegBase);
963 Addr.setReg(ResultReg);
966 if (RegisterOffsetNeedsLowering) {
967 unsigned ResultReg = 0;
969 if (Addr.getExtendType() == AArch64_AM::SXTW ||
970 Addr.getExtendType() == AArch64_AM::UXTW )
971 ResultReg = emitAddSub_rx(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
972 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
973 /*TODO:IsKill=*/false, Addr.getExtendType(),
976 ResultReg = emitAddSub_rs(/*UseAdd=*/true, MVT::i64, Addr.getReg(),
977 /*TODO:IsKill=*/false, Addr.getOffsetReg(),
978 /*TODO:IsKill=*/false, AArch64_AM::LSL,
981 if (Addr.getExtendType() == AArch64_AM::UXTW)
982 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
983 /*Op0IsKill=*/false, Addr.getShift(),
985 else if (Addr.getExtendType() == AArch64_AM::SXTW)
986 ResultReg = emitLSL_ri(MVT::i64, MVT::i32, Addr.getOffsetReg(),
987 /*Op0IsKill=*/false, Addr.getShift(),
990 ResultReg = emitLSL_ri(MVT::i64, MVT::i64, Addr.getOffsetReg(),
991 /*Op0IsKill=*/false, Addr.getShift());
996 Addr.setReg(ResultReg);
997 Addr.setOffsetReg(0);
999 Addr.setExtendType(AArch64_AM::InvalidShiftExtend);
1002 // Since the offset is too large for the load/store instruction get the
1003 // reg+offset into a register.
1004 if (ImmediateOffsetNeedsLowering) {
1007 // Try to fold the immediate into the add instruction.
1008 ResultReg = emitAdd_ri_(MVT::i64, Addr.getReg(), /*IsKill=*/false, Offset);
1010 ResultReg = fastEmit_i(MVT::i64, MVT::i64, ISD::Constant, Offset);
1014 Addr.setReg(ResultReg);
1020 void AArch64FastISel::addLoadStoreOperands(Address &Addr,
1021 const MachineInstrBuilder &MIB,
1023 unsigned ScaleFactor,
1024 MachineMemOperand *MMO) {
1025 int64_t Offset = Addr.getOffset() / ScaleFactor;
1026 // Frame base works a bit differently. Handle it separately.
1027 if (Addr.isFIBase()) {
1028 int FI = Addr.getFI();
1029 // FIXME: We shouldn't be using getObjectSize/getObjectAlignment. The size
1030 // and alignment should be based on the VT.
1031 MMO = FuncInfo.MF->getMachineMemOperand(
1032 MachinePointerInfo::getFixedStack(FI, Offset), Flags,
1033 MFI.getObjectSize(FI), MFI.getObjectAlignment(FI));
1034 // Now add the rest of the operands.
1035 MIB.addFrameIndex(FI).addImm(Offset);
1037 assert(Addr.isRegBase() && "Unexpected address kind.");
1038 const MCInstrDesc &II = MIB->getDesc();
1039 unsigned Idx = (Flags & MachineMemOperand::MOStore) ? 1 : 0;
1041 constrainOperandRegClass(II, Addr.getReg(), II.getNumDefs()+Idx));
1043 constrainOperandRegClass(II, Addr.getOffsetReg(), II.getNumDefs()+Idx+1));
1044 if (Addr.getOffsetReg()) {
1045 assert(Addr.getOffset() == 0 && "Unexpected offset");
1046 bool IsSigned = Addr.getExtendType() == AArch64_AM::SXTW ||
1047 Addr.getExtendType() == AArch64_AM::SXTX;
1048 MIB.addReg(Addr.getReg());
1049 MIB.addReg(Addr.getOffsetReg());
1050 MIB.addImm(IsSigned);
1051 MIB.addImm(Addr.getShift() != 0);
1053 MIB.addReg(Addr.getReg()).addImm(Offset);
1057 MIB.addMemOperand(MMO);
1060 unsigned AArch64FastISel::emitAddSub(bool UseAdd, MVT RetVT, const Value *LHS,
1061 const Value *RHS, bool SetFlags,
1062 bool WantResult, bool IsZExt) {
1063 AArch64_AM::ShiftExtendType ExtendType = AArch64_AM::InvalidShiftExtend;
1064 bool NeedExtend = false;
1065 switch (RetVT.SimpleTy) {
1073 ExtendType = IsZExt ? AArch64_AM::UXTB : AArch64_AM::SXTB;
1077 ExtendType = IsZExt ? AArch64_AM::UXTH : AArch64_AM::SXTH;
1079 case MVT::i32: // fall-through
1084 RetVT.SimpleTy = std::max(RetVT.SimpleTy, MVT::i32);
1086 // Canonicalize immediates to the RHS first.
1087 if (UseAdd && isa<Constant>(LHS) && !isa<Constant>(RHS))
1088 std::swap(LHS, RHS);
1090 // Canonicalize mul by power of 2 to the RHS.
1091 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1092 if (isMulPowOf2(LHS))
1093 std::swap(LHS, RHS);
1095 // Canonicalize shift immediate to the RHS.
1096 if (UseAdd && LHS->hasOneUse() && isValueAvailable(LHS))
1097 if (const auto *SI = dyn_cast<BinaryOperator>(LHS))
1098 if (isa<ConstantInt>(SI->getOperand(1)))
1099 if (SI->getOpcode() == Instruction::Shl ||
1100 SI->getOpcode() == Instruction::LShr ||
1101 SI->getOpcode() == Instruction::AShr )
1102 std::swap(LHS, RHS);
1104 unsigned LHSReg = getRegForValue(LHS);
1107 bool LHSIsKill = hasTrivialKill(LHS);
1110 LHSReg = emitIntExt(SrcVT, LHSReg, RetVT, IsZExt);
1112 unsigned ResultReg = 0;
1113 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1114 uint64_t Imm = IsZExt ? C->getZExtValue() : C->getSExtValue();
1115 if (C->isNegative())
1116 ResultReg = emitAddSub_ri(!UseAdd, RetVT, LHSReg, LHSIsKill, -Imm,
1117 SetFlags, WantResult);
1119 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, Imm, SetFlags,
1121 } else if (const auto *C = dyn_cast<Constant>(RHS))
1122 if (C->isNullValue())
1123 ResultReg = emitAddSub_ri(UseAdd, RetVT, LHSReg, LHSIsKill, 0, SetFlags,
1129 // Only extend the RHS within the instruction if there is a valid extend type.
1130 if (ExtendType != AArch64_AM::InvalidShiftExtend && RHS->hasOneUse() &&
1131 isValueAvailable(RHS)) {
1132 if (const auto *SI = dyn_cast<BinaryOperator>(RHS))
1133 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1)))
1134 if ((SI->getOpcode() == Instruction::Shl) && (C->getZExtValue() < 4)) {
1135 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1138 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1139 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1140 RHSIsKill, ExtendType, C->getZExtValue(),
1141 SetFlags, WantResult);
1143 unsigned RHSReg = getRegForValue(RHS);
1146 bool RHSIsKill = hasTrivialKill(RHS);
1147 return emitAddSub_rx(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1148 ExtendType, 0, SetFlags, WantResult);
1151 // Check if the mul can be folded into the instruction.
1152 if (RHS->hasOneUse() && isValueAvailable(RHS))
1153 if (isMulPowOf2(RHS)) {
1154 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1155 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1157 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1158 if (C->getValue().isPowerOf2())
1159 std::swap(MulLHS, MulRHS);
1161 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1162 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1163 unsigned RHSReg = getRegForValue(MulLHS);
1166 bool RHSIsKill = hasTrivialKill(MulLHS);
1167 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1168 AArch64_AM::LSL, ShiftVal, SetFlags, WantResult);
1171 // Check if the shift can be folded into the instruction.
1172 if (RHS->hasOneUse() && isValueAvailable(RHS))
1173 if (const auto *SI = dyn_cast<BinaryOperator>(RHS)) {
1174 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1175 AArch64_AM::ShiftExtendType ShiftType = AArch64_AM::InvalidShiftExtend;
1176 switch (SI->getOpcode()) {
1178 case Instruction::Shl: ShiftType = AArch64_AM::LSL; break;
1179 case Instruction::LShr: ShiftType = AArch64_AM::LSR; break;
1180 case Instruction::AShr: ShiftType = AArch64_AM::ASR; break;
1182 uint64_t ShiftVal = C->getZExtValue();
1183 if (ShiftType != AArch64_AM::InvalidShiftExtend) {
1184 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1187 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1188 return emitAddSub_rs(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg,
1189 RHSIsKill, ShiftType, ShiftVal, SetFlags,
1195 unsigned RHSReg = getRegForValue(RHS);
1198 bool RHSIsKill = hasTrivialKill(RHS);
1201 RHSReg = emitIntExt(SrcVT, RHSReg, RetVT, IsZExt);
1203 return emitAddSub_rr(UseAdd, RetVT, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1204 SetFlags, WantResult);
1207 unsigned AArch64FastISel::emitAddSub_rr(bool UseAdd, MVT RetVT, unsigned LHSReg,
1208 bool LHSIsKill, unsigned RHSReg,
1209 bool RHSIsKill, bool SetFlags,
1211 assert(LHSReg && RHSReg && "Invalid register number.");
1213 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1216 static const unsigned OpcTable[2][2][2] = {
1217 { { AArch64::SUBWrr, AArch64::SUBXrr },
1218 { AArch64::ADDWrr, AArch64::ADDXrr } },
1219 { { AArch64::SUBSWrr, AArch64::SUBSXrr },
1220 { AArch64::ADDSWrr, AArch64::ADDSXrr } }
1222 bool Is64Bit = RetVT == MVT::i64;
1223 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1224 const TargetRegisterClass *RC =
1225 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1228 ResultReg = createResultReg(RC);
1230 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1232 const MCInstrDesc &II = TII.get(Opc);
1233 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1234 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1235 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1236 .addReg(LHSReg, getKillRegState(LHSIsKill))
1237 .addReg(RHSReg, getKillRegState(RHSIsKill));
1241 unsigned AArch64FastISel::emitAddSub_ri(bool UseAdd, MVT RetVT, unsigned LHSReg,
1242 bool LHSIsKill, uint64_t Imm,
1243 bool SetFlags, bool WantResult) {
1244 assert(LHSReg && "Invalid register number.");
1246 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1250 if (isUInt<12>(Imm))
1252 else if ((Imm & 0xfff000) == Imm) {
1258 static const unsigned OpcTable[2][2][2] = {
1259 { { AArch64::SUBWri, AArch64::SUBXri },
1260 { AArch64::ADDWri, AArch64::ADDXri } },
1261 { { AArch64::SUBSWri, AArch64::SUBSXri },
1262 { AArch64::ADDSWri, AArch64::ADDSXri } }
1264 bool Is64Bit = RetVT == MVT::i64;
1265 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1266 const TargetRegisterClass *RC;
1268 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1270 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1273 ResultReg = createResultReg(RC);
1275 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1277 const MCInstrDesc &II = TII.get(Opc);
1278 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1280 .addReg(LHSReg, getKillRegState(LHSIsKill))
1282 .addImm(getShifterImm(AArch64_AM::LSL, ShiftImm));
1286 unsigned AArch64FastISel::emitAddSub_rs(bool UseAdd, MVT RetVT, unsigned LHSReg,
1287 bool LHSIsKill, unsigned RHSReg,
1289 AArch64_AM::ShiftExtendType ShiftType,
1290 uint64_t ShiftImm, bool SetFlags,
1292 assert(LHSReg && RHSReg && "Invalid register number.");
1294 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1297 static const unsigned OpcTable[2][2][2] = {
1298 { { AArch64::SUBWrs, AArch64::SUBXrs },
1299 { AArch64::ADDWrs, AArch64::ADDXrs } },
1300 { { AArch64::SUBSWrs, AArch64::SUBSXrs },
1301 { AArch64::ADDSWrs, AArch64::ADDSXrs } }
1303 bool Is64Bit = RetVT == MVT::i64;
1304 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1305 const TargetRegisterClass *RC =
1306 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1309 ResultReg = createResultReg(RC);
1311 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1313 const MCInstrDesc &II = TII.get(Opc);
1314 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1315 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1316 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1317 .addReg(LHSReg, getKillRegState(LHSIsKill))
1318 .addReg(RHSReg, getKillRegState(RHSIsKill))
1319 .addImm(getShifterImm(ShiftType, ShiftImm));
1323 unsigned AArch64FastISel::emitAddSub_rx(bool UseAdd, MVT RetVT, unsigned LHSReg,
1324 bool LHSIsKill, unsigned RHSReg,
1326 AArch64_AM::ShiftExtendType ExtType,
1327 uint64_t ShiftImm, bool SetFlags,
1329 assert(LHSReg && RHSReg && "Invalid register number.");
1331 if (RetVT != MVT::i32 && RetVT != MVT::i64)
1334 static const unsigned OpcTable[2][2][2] = {
1335 { { AArch64::SUBWrx, AArch64::SUBXrx },
1336 { AArch64::ADDWrx, AArch64::ADDXrx } },
1337 { { AArch64::SUBSWrx, AArch64::SUBSXrx },
1338 { AArch64::ADDSWrx, AArch64::ADDSXrx } }
1340 bool Is64Bit = RetVT == MVT::i64;
1341 unsigned Opc = OpcTable[SetFlags][UseAdd][Is64Bit];
1342 const TargetRegisterClass *RC = nullptr;
1344 RC = Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
1346 RC = Is64Bit ? &AArch64::GPR64spRegClass : &AArch64::GPR32spRegClass;
1349 ResultReg = createResultReg(RC);
1351 ResultReg = Is64Bit ? AArch64::XZR : AArch64::WZR;
1353 const MCInstrDesc &II = TII.get(Opc);
1354 LHSReg = constrainOperandRegClass(II, LHSReg, II.getNumDefs());
1355 RHSReg = constrainOperandRegClass(II, RHSReg, II.getNumDefs() + 1);
1356 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II, ResultReg)
1357 .addReg(LHSReg, getKillRegState(LHSIsKill))
1358 .addReg(RHSReg, getKillRegState(RHSIsKill))
1359 .addImm(getArithExtendImm(ExtType, ShiftImm));
1363 bool AArch64FastISel::emitCmp(const Value *LHS, const Value *RHS, bool IsZExt) {
1364 Type *Ty = LHS->getType();
1365 EVT EVT = TLI.getValueType(Ty, true);
1366 if (!EVT.isSimple())
1368 MVT VT = EVT.getSimpleVT();
1370 switch (VT.SimpleTy) {
1378 return emitICmp(VT, LHS, RHS, IsZExt);
1381 return emitFCmp(VT, LHS, RHS);
1385 bool AArch64FastISel::emitICmp(MVT RetVT, const Value *LHS, const Value *RHS,
1387 return emitSub(RetVT, LHS, RHS, /*SetFlags=*/true, /*WantResult=*/false,
1391 bool AArch64FastISel::emitICmp_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1393 return emitAddSub_ri(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, Imm,
1394 /*SetFlags=*/true, /*WantResult=*/false) != 0;
1397 bool AArch64FastISel::emitFCmp(MVT RetVT, const Value *LHS, const Value *RHS) {
1398 if (RetVT != MVT::f32 && RetVT != MVT::f64)
1401 // Check to see if the 2nd operand is a constant that we can encode directly
1403 bool UseImm = false;
1404 if (const auto *CFP = dyn_cast<ConstantFP>(RHS))
1405 if (CFP->isZero() && !CFP->isNegative())
1408 unsigned LHSReg = getRegForValue(LHS);
1411 bool LHSIsKill = hasTrivialKill(LHS);
1414 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDri : AArch64::FCMPSri;
1415 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1416 .addReg(LHSReg, getKillRegState(LHSIsKill));
1420 unsigned RHSReg = getRegForValue(RHS);
1423 bool RHSIsKill = hasTrivialKill(RHS);
1425 unsigned Opc = (RetVT == MVT::f64) ? AArch64::FCMPDrr : AArch64::FCMPSrr;
1426 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
1427 .addReg(LHSReg, getKillRegState(LHSIsKill))
1428 .addReg(RHSReg, getKillRegState(RHSIsKill));
1432 unsigned AArch64FastISel::emitAdd(MVT RetVT, const Value *LHS, const Value *RHS,
1433 bool SetFlags, bool WantResult, bool IsZExt) {
1434 return emitAddSub(/*UseAdd=*/true, RetVT, LHS, RHS, SetFlags, WantResult,
1438 /// \brief This method is a wrapper to simplify add emission.
1440 /// First try to emit an add with an immediate operand using emitAddSub_ri. If
1441 /// that fails, then try to materialize the immediate into a register and use
1442 /// emitAddSub_rr instead.
1443 unsigned AArch64FastISel::emitAdd_ri_(MVT VT, unsigned Op0, bool Op0IsKill,
1447 ResultReg = emitAddSub_ri(false, VT, Op0, Op0IsKill, -Imm);
1449 ResultReg = emitAddSub_ri(true, VT, Op0, Op0IsKill, Imm);
1454 unsigned CReg = fastEmit_i(VT, VT, ISD::Constant, Imm);
1458 ResultReg = emitAddSub_rr(true, VT, Op0, Op0IsKill, CReg, true);
1462 unsigned AArch64FastISel::emitSub(MVT RetVT, const Value *LHS, const Value *RHS,
1463 bool SetFlags, bool WantResult, bool IsZExt) {
1464 return emitAddSub(/*UseAdd=*/false, RetVT, LHS, RHS, SetFlags, WantResult,
1468 unsigned AArch64FastISel::emitSubs_rr(MVT RetVT, unsigned LHSReg,
1469 bool LHSIsKill, unsigned RHSReg,
1470 bool RHSIsKill, bool WantResult) {
1471 return emitAddSub_rr(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1472 RHSIsKill, /*SetFlags=*/true, WantResult);
1475 unsigned AArch64FastISel::emitSubs_rs(MVT RetVT, unsigned LHSReg,
1476 bool LHSIsKill, unsigned RHSReg,
1478 AArch64_AM::ShiftExtendType ShiftType,
1479 uint64_t ShiftImm, bool WantResult) {
1480 return emitAddSub_rs(/*UseAdd=*/false, RetVT, LHSReg, LHSIsKill, RHSReg,
1481 RHSIsKill, ShiftType, ShiftImm, /*SetFlags=*/true,
1485 unsigned AArch64FastISel::emitLogicalOp(unsigned ISDOpc, MVT RetVT,
1486 const Value *LHS, const Value *RHS) {
1487 // Canonicalize immediates to the RHS first.
1488 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS))
1489 std::swap(LHS, RHS);
1491 // Canonicalize mul by power-of-2 to the RHS.
1492 if (LHS->hasOneUse() && isValueAvailable(LHS))
1493 if (isMulPowOf2(LHS))
1494 std::swap(LHS, RHS);
1496 // Canonicalize shift immediate to the RHS.
1497 if (LHS->hasOneUse() && isValueAvailable(LHS))
1498 if (const auto *SI = dyn_cast<ShlOperator>(LHS))
1499 if (isa<ConstantInt>(SI->getOperand(1)))
1500 std::swap(LHS, RHS);
1502 unsigned LHSReg = getRegForValue(LHS);
1505 bool LHSIsKill = hasTrivialKill(LHS);
1507 unsigned ResultReg = 0;
1508 if (const auto *C = dyn_cast<ConstantInt>(RHS)) {
1509 uint64_t Imm = C->getZExtValue();
1510 ResultReg = emitLogicalOp_ri(ISDOpc, RetVT, LHSReg, LHSIsKill, Imm);
1515 // Check if the mul can be folded into the instruction.
1516 if (RHS->hasOneUse() && isValueAvailable(RHS))
1517 if (isMulPowOf2(RHS)) {
1518 const Value *MulLHS = cast<MulOperator>(RHS)->getOperand(0);
1519 const Value *MulRHS = cast<MulOperator>(RHS)->getOperand(1);
1521 if (const auto *C = dyn_cast<ConstantInt>(MulLHS))
1522 if (C->getValue().isPowerOf2())
1523 std::swap(MulLHS, MulRHS);
1525 assert(isa<ConstantInt>(MulRHS) && "Expected a ConstantInt.");
1526 uint64_t ShiftVal = cast<ConstantInt>(MulRHS)->getValue().logBase2();
1528 unsigned RHSReg = getRegForValue(MulLHS);
1531 bool RHSIsKill = hasTrivialKill(MulLHS);
1532 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1533 RHSIsKill, ShiftVal);
1536 // Check if the shift can be folded into the instruction.
1537 if (RHS->hasOneUse() && isValueAvailable(RHS))
1538 if (const auto *SI = dyn_cast<ShlOperator>(RHS))
1539 if (const auto *C = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1540 uint64_t ShiftVal = C->getZExtValue();
1541 unsigned RHSReg = getRegForValue(SI->getOperand(0));
1544 bool RHSIsKill = hasTrivialKill(SI->getOperand(0));
1545 return emitLogicalOp_rs(ISDOpc, RetVT, LHSReg, LHSIsKill, RHSReg,
1546 RHSIsKill, ShiftVal);
1549 unsigned RHSReg = getRegForValue(RHS);
1552 bool RHSIsKill = hasTrivialKill(RHS);
1554 MVT VT = std::max(MVT::i32, RetVT.SimpleTy);
1555 ResultReg = fastEmit_rr(VT, VT, ISDOpc, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
1556 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1557 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1558 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1563 unsigned AArch64FastISel::emitLogicalOp_ri(unsigned ISDOpc, MVT RetVT,
1564 unsigned LHSReg, bool LHSIsKill,
1566 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1567 "ISD nodes are not consecutive!");
1568 static const unsigned OpcTable[3][2] = {
1569 { AArch64::ANDWri, AArch64::ANDXri },
1570 { AArch64::ORRWri, AArch64::ORRXri },
1571 { AArch64::EORWri, AArch64::EORXri }
1573 const TargetRegisterClass *RC;
1576 switch (RetVT.SimpleTy) {
1583 unsigned Idx = ISDOpc - ISD::AND;
1584 Opc = OpcTable[Idx][0];
1585 RC = &AArch64::GPR32spRegClass;
1590 Opc = OpcTable[ISDOpc - ISD::AND][1];
1591 RC = &AArch64::GPR64spRegClass;
1596 if (!AArch64_AM::isLogicalImmediate(Imm, RegSize))
1599 unsigned ResultReg =
1600 fastEmitInst_ri(Opc, RC, LHSReg, LHSIsKill,
1601 AArch64_AM::encodeLogicalImmediate(Imm, RegSize));
1602 if (RetVT >= MVT::i8 && RetVT <= MVT::i16 && ISDOpc != ISD::AND) {
1603 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1604 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1609 unsigned AArch64FastISel::emitLogicalOp_rs(unsigned ISDOpc, MVT RetVT,
1610 unsigned LHSReg, bool LHSIsKill,
1611 unsigned RHSReg, bool RHSIsKill,
1612 uint64_t ShiftImm) {
1613 assert((ISD::AND + 1 == ISD::OR) && (ISD::AND + 2 == ISD::XOR) &&
1614 "ISD nodes are not consecutive!");
1615 static const unsigned OpcTable[3][2] = {
1616 { AArch64::ANDWrs, AArch64::ANDXrs },
1617 { AArch64::ORRWrs, AArch64::ORRXrs },
1618 { AArch64::EORWrs, AArch64::EORXrs }
1620 const TargetRegisterClass *RC;
1622 switch (RetVT.SimpleTy) {
1629 Opc = OpcTable[ISDOpc - ISD::AND][0];
1630 RC = &AArch64::GPR32RegClass;
1633 Opc = OpcTable[ISDOpc - ISD::AND][1];
1634 RC = &AArch64::GPR64RegClass;
1637 unsigned ResultReg =
1638 fastEmitInst_rri(Opc, RC, LHSReg, LHSIsKill, RHSReg, RHSIsKill,
1639 AArch64_AM::getShifterImm(AArch64_AM::LSL, ShiftImm));
1640 if (RetVT >= MVT::i8 && RetVT <= MVT::i16) {
1641 uint64_t Mask = (RetVT == MVT::i8) ? 0xff : 0xffff;
1642 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
1647 unsigned AArch64FastISel::emitAnd_ri(MVT RetVT, unsigned LHSReg, bool LHSIsKill,
1649 return emitLogicalOp_ri(ISD::AND, RetVT, LHSReg, LHSIsKill, Imm);
1652 unsigned AArch64FastISel::emitLoad(MVT VT, MVT RetVT, Address Addr,
1653 bool WantZExt, MachineMemOperand *MMO) {
1654 // Simplify this down to something we can handle.
1655 if (!simplifyAddress(Addr, VT))
1658 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1660 llvm_unreachable("Unexpected value type.");
1662 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1663 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1664 bool UseScaled = true;
1665 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1670 static const unsigned GPOpcTable[2][8][4] = {
1672 { { AArch64::LDURSBWi, AArch64::LDURSHWi, AArch64::LDURWi,
1674 { AArch64::LDURSBXi, AArch64::LDURSHXi, AArch64::LDURSWi,
1676 { AArch64::LDRSBWui, AArch64::LDRSHWui, AArch64::LDRWui,
1678 { AArch64::LDRSBXui, AArch64::LDRSHXui, AArch64::LDRSWui,
1680 { AArch64::LDRSBWroX, AArch64::LDRSHWroX, AArch64::LDRWroX,
1682 { AArch64::LDRSBXroX, AArch64::LDRSHXroX, AArch64::LDRSWroX,
1684 { AArch64::LDRSBWroW, AArch64::LDRSHWroW, AArch64::LDRWroW,
1686 { AArch64::LDRSBXroW, AArch64::LDRSHXroW, AArch64::LDRSWroW,
1690 { { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1692 { AArch64::LDURBBi, AArch64::LDURHHi, AArch64::LDURWi,
1694 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1696 { AArch64::LDRBBui, AArch64::LDRHHui, AArch64::LDRWui,
1698 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1700 { AArch64::LDRBBroX, AArch64::LDRHHroX, AArch64::LDRWroX,
1702 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1704 { AArch64::LDRBBroW, AArch64::LDRHHroW, AArch64::LDRWroW,
1709 static const unsigned FPOpcTable[4][2] = {
1710 { AArch64::LDURSi, AArch64::LDURDi },
1711 { AArch64::LDRSui, AArch64::LDRDui },
1712 { AArch64::LDRSroX, AArch64::LDRDroX },
1713 { AArch64::LDRSroW, AArch64::LDRDroW }
1717 const TargetRegisterClass *RC;
1718 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1719 Addr.getOffsetReg();
1720 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1721 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1722 Addr.getExtendType() == AArch64_AM::SXTW)
1725 bool IsRet64Bit = RetVT == MVT::i64;
1726 switch (VT.SimpleTy) {
1728 llvm_unreachable("Unexpected value type.");
1729 case MVT::i1: // Intentional fall-through.
1731 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][0];
1732 RC = (IsRet64Bit && !WantZExt) ?
1733 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1736 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][1];
1737 RC = (IsRet64Bit && !WantZExt) ?
1738 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1741 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][2];
1742 RC = (IsRet64Bit && !WantZExt) ?
1743 &AArch64::GPR64RegClass: &AArch64::GPR32RegClass;
1746 Opc = GPOpcTable[WantZExt][2 * Idx + IsRet64Bit][3];
1747 RC = &AArch64::GPR64RegClass;
1750 Opc = FPOpcTable[Idx][0];
1751 RC = &AArch64::FPR32RegClass;
1754 Opc = FPOpcTable[Idx][1];
1755 RC = &AArch64::FPR64RegClass;
1759 // Create the base instruction, then add the operands.
1760 unsigned ResultReg = createResultReg(RC);
1761 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1762 TII.get(Opc), ResultReg);
1763 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOLoad, ScaleFactor, MMO);
1765 // Loading an i1 requires special handling.
1766 if (VT == MVT::i1) {
1767 unsigned ANDReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, 1);
1768 assert(ANDReg && "Unexpected AND instruction emission failure.");
1772 // For zero-extending loads to 64bit we emit a 32bit load and then convert
1773 // the 32bit reg to a 64bit reg.
1774 if (WantZExt && RetVT == MVT::i64 && VT <= MVT::i32) {
1775 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
1776 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
1777 TII.get(AArch64::SUBREG_TO_REG), Reg64)
1779 .addReg(ResultReg, getKillRegState(true))
1780 .addImm(AArch64::sub_32);
1786 bool AArch64FastISel::selectAddSub(const Instruction *I) {
1788 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1792 return selectOperator(I, I->getOpcode());
1795 switch (I->getOpcode()) {
1797 llvm_unreachable("Unexpected instruction.");
1798 case Instruction::Add:
1799 ResultReg = emitAdd(VT, I->getOperand(0), I->getOperand(1));
1801 case Instruction::Sub:
1802 ResultReg = emitSub(VT, I->getOperand(0), I->getOperand(1));
1808 updateValueMap(I, ResultReg);
1812 bool AArch64FastISel::selectLogicalOp(const Instruction *I) {
1814 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
1818 return selectOperator(I, I->getOpcode());
1821 switch (I->getOpcode()) {
1823 llvm_unreachable("Unexpected instruction.");
1824 case Instruction::And:
1825 ResultReg = emitLogicalOp(ISD::AND, VT, I->getOperand(0), I->getOperand(1));
1827 case Instruction::Or:
1828 ResultReg = emitLogicalOp(ISD::OR, VT, I->getOperand(0), I->getOperand(1));
1830 case Instruction::Xor:
1831 ResultReg = emitLogicalOp(ISD::XOR, VT, I->getOperand(0), I->getOperand(1));
1837 updateValueMap(I, ResultReg);
1841 bool AArch64FastISel::selectLoad(const Instruction *I) {
1843 // Verify we have a legal type before going any further. Currently, we handle
1844 // simple types that will directly fit in a register (i32/f32/i64/f64) or
1845 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
1846 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true) ||
1847 cast<LoadInst>(I)->isAtomic())
1850 // See if we can handle this address.
1852 if (!computeAddress(I->getOperand(0), Addr, I->getType()))
1855 // Fold the following sign-/zero-extend into the load instruction.
1856 bool WantZExt = true;
1858 const Value *IntExtVal = nullptr;
1859 if (I->hasOneUse()) {
1860 if (const auto *ZE = dyn_cast<ZExtInst>(I->use_begin()->getUser())) {
1861 if (isTypeSupported(ZE->getType(), RetVT))
1865 } else if (const auto *SE = dyn_cast<SExtInst>(I->use_begin()->getUser())) {
1866 if (isTypeSupported(SE->getType(), RetVT))
1874 unsigned ResultReg =
1875 emitLoad(VT, RetVT, Addr, WantZExt, createMachineMemOperandFor(I));
1879 // There are a few different cases we have to handle, because the load or the
1880 // sign-/zero-extend might not be selected by FastISel if we fall-back to
1881 // SelectionDAG. There is also an ordering issue when both instructions are in
1882 // different basic blocks.
1883 // 1.) The load instruction is selected by FastISel, but the integer extend
1884 // not. This usually happens when the integer extend is in a different
1885 // basic block and SelectionDAG took over for that basic block.
1886 // 2.) The load instruction is selected before the integer extend. This only
1887 // happens when the integer extend is in a different basic block.
1888 // 3.) The load instruction is selected by SelectionDAG and the integer extend
1889 // by FastISel. This happens if there are instructions between the load
1890 // and the integer extend that couldn't be selected by FastISel.
1892 // The integer extend hasn't been emitted yet. FastISel or SelectionDAG
1893 // could select it. Emit a copy to subreg if necessary. FastISel will remove
1894 // it when it selects the integer extend.
1895 unsigned Reg = lookUpRegForValue(IntExtVal);
1897 if (RetVT == MVT::i64 && VT <= MVT::i32) {
1899 // Delete the last emitted instruction from emitLoad (SUBREG_TO_REG).
1900 std::prev(FuncInfo.InsertPt)->eraseFromParent();
1901 ResultReg = std::prev(FuncInfo.InsertPt)->getOperand(0).getReg();
1903 ResultReg = fastEmitInst_extractsubreg(MVT::i32, ResultReg,
1907 updateValueMap(I, ResultReg);
1911 // The integer extend has already been emitted - delete all the instructions
1912 // that have been emitted by the integer extend lowering code and use the
1913 // result from the load instruction directly.
1915 auto *MI = MRI.getUniqueVRegDef(Reg);
1919 for (auto &Opnd : MI->uses()) {
1921 Reg = Opnd.getReg();
1925 MI->eraseFromParent();
1927 updateValueMap(IntExtVal, ResultReg);
1931 updateValueMap(I, ResultReg);
1935 bool AArch64FastISel::emitStore(MVT VT, unsigned SrcReg, Address Addr,
1936 MachineMemOperand *MMO) {
1937 // Simplify this down to something we can handle.
1938 if (!simplifyAddress(Addr, VT))
1941 unsigned ScaleFactor = getImplicitScaleFactor(VT);
1943 llvm_unreachable("Unexpected value type.");
1945 // Negative offsets require unscaled, 9-bit, signed immediate offsets.
1946 // Otherwise, we try using scaled, 12-bit, unsigned immediate offsets.
1947 bool UseScaled = true;
1948 if ((Addr.getOffset() < 0) || (Addr.getOffset() & (ScaleFactor - 1))) {
1953 static const unsigned OpcTable[4][6] = {
1954 { AArch64::STURBBi, AArch64::STURHHi, AArch64::STURWi, AArch64::STURXi,
1955 AArch64::STURSi, AArch64::STURDi },
1956 { AArch64::STRBBui, AArch64::STRHHui, AArch64::STRWui, AArch64::STRXui,
1957 AArch64::STRSui, AArch64::STRDui },
1958 { AArch64::STRBBroX, AArch64::STRHHroX, AArch64::STRWroX, AArch64::STRXroX,
1959 AArch64::STRSroX, AArch64::STRDroX },
1960 { AArch64::STRBBroW, AArch64::STRHHroW, AArch64::STRWroW, AArch64::STRXroW,
1961 AArch64::STRSroW, AArch64::STRDroW }
1965 bool VTIsi1 = false;
1966 bool UseRegOffset = Addr.isRegBase() && !Addr.getOffset() && Addr.getReg() &&
1967 Addr.getOffsetReg();
1968 unsigned Idx = UseRegOffset ? 2 : UseScaled ? 1 : 0;
1969 if (Addr.getExtendType() == AArch64_AM::UXTW ||
1970 Addr.getExtendType() == AArch64_AM::SXTW)
1973 switch (VT.SimpleTy) {
1974 default: llvm_unreachable("Unexpected value type.");
1975 case MVT::i1: VTIsi1 = true;
1976 case MVT::i8: Opc = OpcTable[Idx][0]; break;
1977 case MVT::i16: Opc = OpcTable[Idx][1]; break;
1978 case MVT::i32: Opc = OpcTable[Idx][2]; break;
1979 case MVT::i64: Opc = OpcTable[Idx][3]; break;
1980 case MVT::f32: Opc = OpcTable[Idx][4]; break;
1981 case MVT::f64: Opc = OpcTable[Idx][5]; break;
1984 // Storing an i1 requires special handling.
1985 if (VTIsi1 && SrcReg != AArch64::WZR) {
1986 unsigned ANDReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
1987 assert(ANDReg && "Unexpected AND instruction emission failure.");
1990 // Create the base instruction, then add the operands.
1991 const MCInstrDesc &II = TII.get(Opc);
1992 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
1993 MachineInstrBuilder MIB =
1994 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(SrcReg);
1995 addLoadStoreOperands(Addr, MIB, MachineMemOperand::MOStore, ScaleFactor, MMO);
2000 bool AArch64FastISel::selectStore(const Instruction *I) {
2002 const Value *Op0 = I->getOperand(0);
2003 // Verify we have a legal type before going any further. Currently, we handle
2004 // simple types that will directly fit in a register (i32/f32/i64/f64) or
2005 // those that can be sign or zero-extended to a basic operation (i1/i8/i16).
2006 if (!isTypeSupported(Op0->getType(), VT, /*IsVectorAllowed=*/true) ||
2007 cast<StoreInst>(I)->isAtomic())
2010 // Get the value to be stored into a register. Use the zero register directly
2011 // when possible to avoid an unnecessary copy and a wasted register.
2012 unsigned SrcReg = 0;
2013 if (const auto *CI = dyn_cast<ConstantInt>(Op0)) {
2015 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2016 } else if (const auto *CF = dyn_cast<ConstantFP>(Op0)) {
2017 if (CF->isZero() && !CF->isNegative()) {
2018 VT = MVT::getIntegerVT(VT.getSizeInBits());
2019 SrcReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
2024 SrcReg = getRegForValue(Op0);
2029 // See if we can handle this address.
2031 if (!computeAddress(I->getOperand(1), Addr, I->getOperand(0)->getType()))
2034 if (!emitStore(VT, SrcReg, Addr, createMachineMemOperandFor(I)))
2039 static AArch64CC::CondCode getCompareCC(CmpInst::Predicate Pred) {
2041 case CmpInst::FCMP_ONE:
2042 case CmpInst::FCMP_UEQ:
2044 // AL is our "false" for now. The other two need more compares.
2045 return AArch64CC::AL;
2046 case CmpInst::ICMP_EQ:
2047 case CmpInst::FCMP_OEQ:
2048 return AArch64CC::EQ;
2049 case CmpInst::ICMP_SGT:
2050 case CmpInst::FCMP_OGT:
2051 return AArch64CC::GT;
2052 case CmpInst::ICMP_SGE:
2053 case CmpInst::FCMP_OGE:
2054 return AArch64CC::GE;
2055 case CmpInst::ICMP_UGT:
2056 case CmpInst::FCMP_UGT:
2057 return AArch64CC::HI;
2058 case CmpInst::FCMP_OLT:
2059 return AArch64CC::MI;
2060 case CmpInst::ICMP_ULE:
2061 case CmpInst::FCMP_OLE:
2062 return AArch64CC::LS;
2063 case CmpInst::FCMP_ORD:
2064 return AArch64CC::VC;
2065 case CmpInst::FCMP_UNO:
2066 return AArch64CC::VS;
2067 case CmpInst::FCMP_UGE:
2068 return AArch64CC::PL;
2069 case CmpInst::ICMP_SLT:
2070 case CmpInst::FCMP_ULT:
2071 return AArch64CC::LT;
2072 case CmpInst::ICMP_SLE:
2073 case CmpInst::FCMP_ULE:
2074 return AArch64CC::LE;
2075 case CmpInst::FCMP_UNE:
2076 case CmpInst::ICMP_NE:
2077 return AArch64CC::NE;
2078 case CmpInst::ICMP_UGE:
2079 return AArch64CC::HS;
2080 case CmpInst::ICMP_ULT:
2081 return AArch64CC::LO;
2085 /// \brief Try to emit a combined compare-and-branch instruction.
2086 bool AArch64FastISel::emitCompareAndBranch(const BranchInst *BI) {
2087 assert(isa<CmpInst>(BI->getCondition()) && "Expected cmp instruction");
2088 const CmpInst *CI = cast<CmpInst>(BI->getCondition());
2089 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2091 const Value *LHS = CI->getOperand(0);
2092 const Value *RHS = CI->getOperand(1);
2095 if (!isTypeSupported(LHS->getType(), VT))
2098 unsigned BW = VT.getSizeInBits();
2102 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2103 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2105 // Try to take advantage of fallthrough opportunities.
2106 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2107 std::swap(TBB, FBB);
2108 Predicate = CmpInst::getInversePredicate(Predicate);
2113 if ((Predicate == CmpInst::ICMP_EQ) || (Predicate == CmpInst::ICMP_NE)) {
2114 if (const auto *C = dyn_cast<Constant>(LHS))
2115 if (C->isNullValue())
2116 std::swap(LHS, RHS);
2118 if (!isa<Constant>(RHS))
2121 if (!cast<Constant>(RHS)->isNullValue())
2124 if (const auto *AI = dyn_cast<BinaryOperator>(LHS))
2125 if (AI->getOpcode() == Instruction::And && isValueAvailable(AI)) {
2126 const Value *AndLHS = AI->getOperand(0);
2127 const Value *AndRHS = AI->getOperand(1);
2129 if (const auto *C = dyn_cast<ConstantInt>(AndLHS))
2130 if (C->getValue().isPowerOf2())
2131 std::swap(AndLHS, AndRHS);
2133 if (const auto *C = dyn_cast<ConstantInt>(AndRHS))
2134 if (C->getValue().isPowerOf2()) {
2135 TestBit = C->getValue().logBase2();
2143 IsCmpNE = Predicate == CmpInst::ICMP_NE;
2144 } else if (Predicate == CmpInst::ICMP_SLT) {
2145 if (!isa<Constant>(RHS))
2148 if (!cast<Constant>(RHS)->isNullValue())
2153 } else if (Predicate == CmpInst::ICMP_SGT) {
2154 if (!isa<ConstantInt>(RHS))
2157 if (cast<ConstantInt>(RHS)->getValue() != -1)
2165 static const unsigned OpcTable[2][2][2] = {
2166 { {AArch64::CBZW, AArch64::CBZX },
2167 {AArch64::CBNZW, AArch64::CBNZX} },
2168 { {AArch64::TBZW, AArch64::TBZX },
2169 {AArch64::TBNZW, AArch64::TBNZX} }
2172 bool IsBitTest = TestBit != -1;
2173 bool Is64Bit = BW == 64;
2174 if (TestBit < 32 && TestBit >= 0)
2177 unsigned Opc = OpcTable[IsBitTest][IsCmpNE][Is64Bit];
2178 const MCInstrDesc &II = TII.get(Opc);
2180 unsigned SrcReg = getRegForValue(LHS);
2183 bool SrcIsKill = hasTrivialKill(LHS);
2185 if (BW == 64 && !Is64Bit)
2186 SrcReg = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
2189 if ((BW < 32) && !IsBitTest)
2190 SrcReg = emitIntExt(VT, SrcReg, MVT::i32, /*IsZExt=*/true);
2192 // Emit the combined compare and branch instruction.
2193 SrcReg = constrainOperandRegClass(II, SrcReg, II.getNumDefs());
2194 MachineInstrBuilder MIB =
2195 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc))
2196 .addReg(SrcReg, getKillRegState(SrcIsKill));
2198 MIB.addImm(TestBit);
2201 // Obtain the branch weight and add the TrueBB to the successor list.
2202 uint32_t BranchWeight = 0;
2204 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2205 TBB->getBasicBlock());
2206 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2207 fastEmitBranch(FBB, DbgLoc);
2212 bool AArch64FastISel::selectBranch(const Instruction *I) {
2213 const BranchInst *BI = cast<BranchInst>(I);
2214 if (BI->isUnconditional()) {
2215 MachineBasicBlock *MSucc = FuncInfo.MBBMap[BI->getSuccessor(0)];
2216 fastEmitBranch(MSucc, BI->getDebugLoc());
2220 MachineBasicBlock *TBB = FuncInfo.MBBMap[BI->getSuccessor(0)];
2221 MachineBasicBlock *FBB = FuncInfo.MBBMap[BI->getSuccessor(1)];
2223 AArch64CC::CondCode CC = AArch64CC::NE;
2224 if (const CmpInst *CI = dyn_cast<CmpInst>(BI->getCondition())) {
2225 if (CI->hasOneUse() && isValueAvailable(CI)) {
2226 // Try to optimize or fold the cmp.
2227 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2228 switch (Predicate) {
2231 case CmpInst::FCMP_FALSE:
2232 fastEmitBranch(FBB, DbgLoc);
2234 case CmpInst::FCMP_TRUE:
2235 fastEmitBranch(TBB, DbgLoc);
2239 // Try to emit a combined compare-and-branch first.
2240 if (emitCompareAndBranch(BI))
2243 // Try to take advantage of fallthrough opportunities.
2244 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2245 std::swap(TBB, FBB);
2246 Predicate = CmpInst::getInversePredicate(Predicate);
2250 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2253 // FCMP_UEQ and FCMP_ONE cannot be checked with a single branch
2255 CC = getCompareCC(Predicate);
2256 AArch64CC::CondCode ExtraCC = AArch64CC::AL;
2257 switch (Predicate) {
2260 case CmpInst::FCMP_UEQ:
2261 ExtraCC = AArch64CC::EQ;
2264 case CmpInst::FCMP_ONE:
2265 ExtraCC = AArch64CC::MI;
2269 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2271 // Emit the extra branch for FCMP_UEQ and FCMP_ONE.
2272 if (ExtraCC != AArch64CC::AL) {
2273 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2279 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2283 // Obtain the branch weight and add the TrueBB to the successor list.
2284 uint32_t BranchWeight = 0;
2286 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2287 TBB->getBasicBlock());
2288 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2290 fastEmitBranch(FBB, DbgLoc);
2293 } else if (TruncInst *TI = dyn_cast<TruncInst>(BI->getCondition())) {
2295 if (TI->hasOneUse() && isValueAvailable(TI) &&
2296 isTypeSupported(TI->getOperand(0)->getType(), SrcVT)) {
2297 unsigned CondReg = getRegForValue(TI->getOperand(0));
2300 bool CondIsKill = hasTrivialKill(TI->getOperand(0));
2302 // Issue an extract_subreg to get the lower 32-bits.
2303 if (SrcVT == MVT::i64) {
2304 CondReg = fastEmitInst_extractsubreg(MVT::i32, CondReg, CondIsKill,
2309 unsigned ANDReg = emitAnd_ri(MVT::i32, CondReg, CondIsKill, 1);
2310 assert(ANDReg && "Unexpected AND instruction emission failure.");
2311 emitICmp_ri(MVT::i32, ANDReg, /*IsKill=*/true, 0);
2313 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2314 std::swap(TBB, FBB);
2317 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2321 // Obtain the branch weight and add the TrueBB to the successor list.
2322 uint32_t BranchWeight = 0;
2324 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2325 TBB->getBasicBlock());
2326 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2328 fastEmitBranch(FBB, DbgLoc);
2331 } else if (const auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
2332 uint64_t Imm = CI->getZExtValue();
2333 MachineBasicBlock *Target = (Imm == 0) ? FBB : TBB;
2334 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::B))
2337 // Obtain the branch weight and add the target to the successor list.
2338 uint32_t BranchWeight = 0;
2340 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2341 Target->getBasicBlock());
2342 FuncInfo.MBB->addSuccessor(Target, BranchWeight);
2344 } else if (foldXALUIntrinsic(CC, I, BI->getCondition())) {
2345 // Fake request the condition, otherwise the intrinsic might be completely
2347 unsigned CondReg = getRegForValue(BI->getCondition());
2352 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2356 // Obtain the branch weight and add the TrueBB to the successor list.
2357 uint32_t BranchWeight = 0;
2359 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2360 TBB->getBasicBlock());
2361 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2363 fastEmitBranch(FBB, DbgLoc);
2367 unsigned CondReg = getRegForValue(BI->getCondition());
2370 bool CondRegIsKill = hasTrivialKill(BI->getCondition());
2372 // We've been divorced from our compare! Our block was split, and
2373 // now our compare lives in a predecessor block. We musn't
2374 // re-compare here, as the children of the compare aren't guaranteed
2375 // live across the block boundary (we *could* check for this).
2376 // Regardless, the compare has been done in the predecessor block,
2377 // and it left a value for us in a virtual register. Ergo, we test
2378 // the one-bit value left in the virtual register.
2379 emitICmp_ri(MVT::i32, CondReg, CondRegIsKill, 0);
2381 if (FuncInfo.MBB->isLayoutSuccessor(TBB)) {
2382 std::swap(TBB, FBB);
2386 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::Bcc))
2390 // Obtain the branch weight and add the TrueBB to the successor list.
2391 uint32_t BranchWeight = 0;
2393 BranchWeight = FuncInfo.BPI->getEdgeWeight(BI->getParent(),
2394 TBB->getBasicBlock());
2395 FuncInfo.MBB->addSuccessor(TBB, BranchWeight);
2397 fastEmitBranch(FBB, DbgLoc);
2401 bool AArch64FastISel::selectIndirectBr(const Instruction *I) {
2402 const IndirectBrInst *BI = cast<IndirectBrInst>(I);
2403 unsigned AddrReg = getRegForValue(BI->getOperand(0));
2407 // Emit the indirect branch.
2408 const MCInstrDesc &II = TII.get(AArch64::BR);
2409 AddrReg = constrainOperandRegClass(II, AddrReg, II.getNumDefs());
2410 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(AddrReg);
2412 // Make sure the CFG is up-to-date.
2413 for (unsigned i = 0, e = BI->getNumSuccessors(); i != e; ++i)
2414 FuncInfo.MBB->addSuccessor(FuncInfo.MBBMap[BI->getSuccessor(i)]);
2419 bool AArch64FastISel::selectCmp(const Instruction *I) {
2420 const CmpInst *CI = cast<CmpInst>(I);
2422 // Try to optimize or fold the cmp.
2423 CmpInst::Predicate Predicate = optimizeCmpPredicate(CI);
2424 unsigned ResultReg = 0;
2425 switch (Predicate) {
2428 case CmpInst::FCMP_FALSE:
2429 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2430 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2431 TII.get(TargetOpcode::COPY), ResultReg)
2432 .addReg(AArch64::WZR, getKillRegState(true));
2434 case CmpInst::FCMP_TRUE:
2435 ResultReg = fastEmit_i(MVT::i32, MVT::i32, ISD::Constant, 1);
2440 updateValueMap(I, ResultReg);
2445 if (!emitCmp(CI->getOperand(0), CI->getOperand(1), CI->isUnsigned()))
2448 ResultReg = createResultReg(&AArch64::GPR32RegClass);
2450 // FCMP_UEQ and FCMP_ONE cannot be checked with a single instruction. These
2451 // condition codes are inverted, because they are used by CSINC.
2452 static unsigned CondCodeTable[2][2] = {
2453 { AArch64CC::NE, AArch64CC::VC },
2454 { AArch64CC::PL, AArch64CC::LE }
2456 unsigned *CondCodes = nullptr;
2457 switch (Predicate) {
2460 case CmpInst::FCMP_UEQ:
2461 CondCodes = &CondCodeTable[0][0];
2463 case CmpInst::FCMP_ONE:
2464 CondCodes = &CondCodeTable[1][0];
2469 unsigned TmpReg1 = createResultReg(&AArch64::GPR32RegClass);
2470 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2472 .addReg(AArch64::WZR, getKillRegState(true))
2473 .addReg(AArch64::WZR, getKillRegState(true))
2474 .addImm(CondCodes[0]);
2475 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2477 .addReg(TmpReg1, getKillRegState(true))
2478 .addReg(AArch64::WZR, getKillRegState(true))
2479 .addImm(CondCodes[1]);
2481 updateValueMap(I, ResultReg);
2485 // Now set a register based on the comparison.
2486 AArch64CC::CondCode CC = getCompareCC(Predicate);
2487 assert((CC != AArch64CC::AL) && "Unexpected condition code.");
2488 AArch64CC::CondCode invertedCC = getInvertedCondCode(CC);
2489 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::CSINCWr),
2491 .addReg(AArch64::WZR, getKillRegState(true))
2492 .addReg(AArch64::WZR, getKillRegState(true))
2493 .addImm(invertedCC);
2495 updateValueMap(I, ResultReg);
2499 bool AArch64FastISel::selectSelect(const Instruction *I) {
2500 assert(isa<SelectInst>(I) && "Expected a select instruction.");
2502 if (!isTypeSupported(I->getType(), VT))
2506 const TargetRegisterClass *RC;
2507 switch (VT.SimpleTy) {
2514 Opc = AArch64::CSELWr;
2515 RC = &AArch64::GPR32RegClass;
2518 Opc = AArch64::CSELXr;
2519 RC = &AArch64::GPR64RegClass;
2522 Opc = AArch64::FCSELSrrr;
2523 RC = &AArch64::FPR32RegClass;
2526 Opc = AArch64::FCSELDrrr;
2527 RC = &AArch64::FPR64RegClass;
2531 const SelectInst *SI = cast<SelectInst>(I);
2532 const Value *Cond = SI->getCondition();
2533 AArch64CC::CondCode CC = AArch64CC::NE;
2535 // Try to pickup the flags, so we don't have to emit another compare.
2536 if (foldXALUIntrinsic(CC, I, Cond)) {
2537 // Fake request the condition to force emission of the XALU intrinsic.
2538 unsigned CondReg = getRegForValue(Cond);
2542 unsigned CondReg = getRegForValue(Cond);
2545 bool CondIsKill = hasTrivialKill(Cond);
2547 // Emit a TST instruction (ANDS wzr, reg, #imm).
2548 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ANDSWri),
2550 .addReg(CondReg, getKillRegState(CondIsKill))
2551 .addImm(AArch64_AM::encodeLogicalImmediate(1, 32));
2554 unsigned Src1Reg = getRegForValue(SI->getTrueValue());
2555 bool Src1IsKill = hasTrivialKill(SI->getTrueValue());
2557 unsigned Src2Reg = getRegForValue(SI->getFalseValue());
2558 bool Src2IsKill = hasTrivialKill(SI->getFalseValue());
2560 if (!Src1Reg || !Src2Reg)
2563 unsigned ResultReg = fastEmitInst_rri(Opc, RC, Src1Reg, Src1IsKill, Src2Reg,
2565 updateValueMap(I, ResultReg);
2569 bool AArch64FastISel::selectFPExt(const Instruction *I) {
2570 Value *V = I->getOperand(0);
2571 if (!I->getType()->isDoubleTy() || !V->getType()->isFloatTy())
2574 unsigned Op = getRegForValue(V);
2578 unsigned ResultReg = createResultReg(&AArch64::FPR64RegClass);
2579 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTDSr),
2580 ResultReg).addReg(Op);
2581 updateValueMap(I, ResultReg);
2585 bool AArch64FastISel::selectFPTrunc(const Instruction *I) {
2586 Value *V = I->getOperand(0);
2587 if (!I->getType()->isFloatTy() || !V->getType()->isDoubleTy())
2590 unsigned Op = getRegForValue(V);
2594 unsigned ResultReg = createResultReg(&AArch64::FPR32RegClass);
2595 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::FCVTSDr),
2596 ResultReg).addReg(Op);
2597 updateValueMap(I, ResultReg);
2601 // FPToUI and FPToSI
2602 bool AArch64FastISel::selectFPToInt(const Instruction *I, bool Signed) {
2604 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2607 unsigned SrcReg = getRegForValue(I->getOperand(0));
2611 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2612 if (SrcVT == MVT::f128)
2616 if (SrcVT == MVT::f64) {
2618 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWDr : AArch64::FCVTZSUXDr;
2620 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWDr : AArch64::FCVTZUUXDr;
2623 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZSUWSr : AArch64::FCVTZSUXSr;
2625 Opc = (DestVT == MVT::i32) ? AArch64::FCVTZUUWSr : AArch64::FCVTZUUXSr;
2627 unsigned ResultReg = createResultReg(
2628 DestVT == MVT::i32 ? &AArch64::GPR32RegClass : &AArch64::GPR64RegClass);
2629 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
2631 updateValueMap(I, ResultReg);
2635 bool AArch64FastISel::selectIntToFP(const Instruction *I, bool Signed) {
2637 if (!isTypeLegal(I->getType(), DestVT) || DestVT.isVector())
2639 assert ((DestVT == MVT::f32 || DestVT == MVT::f64) &&
2640 "Unexpected value type.");
2642 unsigned SrcReg = getRegForValue(I->getOperand(0));
2645 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
2647 EVT SrcVT = TLI.getValueType(I->getOperand(0)->getType(), true);
2649 // Handle sign-extension.
2650 if (SrcVT == MVT::i16 || SrcVT == MVT::i8 || SrcVT == MVT::i1) {
2652 emitIntExt(SrcVT.getSimpleVT(), SrcReg, MVT::i32, /*isZExt*/ !Signed);
2659 if (SrcVT == MVT::i64) {
2661 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUXSri : AArch64::SCVTFUXDri;
2663 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUXSri : AArch64::UCVTFUXDri;
2666 Opc = (DestVT == MVT::f32) ? AArch64::SCVTFUWSri : AArch64::SCVTFUWDri;
2668 Opc = (DestVT == MVT::f32) ? AArch64::UCVTFUWSri : AArch64::UCVTFUWDri;
2671 unsigned ResultReg = fastEmitInst_r(Opc, TLI.getRegClassFor(DestVT), SrcReg,
2673 updateValueMap(I, ResultReg);
2677 bool AArch64FastISel::fastLowerArguments() {
2678 if (!FuncInfo.CanLowerReturn)
2681 const Function *F = FuncInfo.Fn;
2685 CallingConv::ID CC = F->getCallingConv();
2686 if (CC != CallingConv::C)
2689 // Only handle simple cases of up to 8 GPR and FPR each.
2690 unsigned GPRCnt = 0;
2691 unsigned FPRCnt = 0;
2693 for (auto const &Arg : F->args()) {
2694 // The first argument is at index 1.
2696 if (F->getAttributes().hasAttribute(Idx, Attribute::ByVal) ||
2697 F->getAttributes().hasAttribute(Idx, Attribute::InReg) ||
2698 F->getAttributes().hasAttribute(Idx, Attribute::StructRet) ||
2699 F->getAttributes().hasAttribute(Idx, Attribute::Nest))
2702 Type *ArgTy = Arg.getType();
2703 if (ArgTy->isStructTy() || ArgTy->isArrayTy())
2706 EVT ArgVT = TLI.getValueType(ArgTy);
2707 if (!ArgVT.isSimple())
2710 MVT VT = ArgVT.getSimpleVT().SimpleTy;
2711 if (VT.isFloatingPoint() && !Subtarget->hasFPARMv8())
2714 if (VT.isVector() &&
2715 (!Subtarget->hasNEON() || !Subtarget->isLittleEndian()))
2718 if (VT >= MVT::i1 && VT <= MVT::i64)
2720 else if ((VT >= MVT::f16 && VT <= MVT::f64) || VT.is64BitVector() ||
2721 VT.is128BitVector())
2726 if (GPRCnt > 8 || FPRCnt > 8)
2730 static const MCPhysReg Registers[6][8] = {
2731 { AArch64::W0, AArch64::W1, AArch64::W2, AArch64::W3, AArch64::W4,
2732 AArch64::W5, AArch64::W6, AArch64::W7 },
2733 { AArch64::X0, AArch64::X1, AArch64::X2, AArch64::X3, AArch64::X4,
2734 AArch64::X5, AArch64::X6, AArch64::X7 },
2735 { AArch64::H0, AArch64::H1, AArch64::H2, AArch64::H3, AArch64::H4,
2736 AArch64::H5, AArch64::H6, AArch64::H7 },
2737 { AArch64::S0, AArch64::S1, AArch64::S2, AArch64::S3, AArch64::S4,
2738 AArch64::S5, AArch64::S6, AArch64::S7 },
2739 { AArch64::D0, AArch64::D1, AArch64::D2, AArch64::D3, AArch64::D4,
2740 AArch64::D5, AArch64::D6, AArch64::D7 },
2741 { AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3, AArch64::Q4,
2742 AArch64::Q5, AArch64::Q6, AArch64::Q7 }
2745 unsigned GPRIdx = 0;
2746 unsigned FPRIdx = 0;
2747 for (auto const &Arg : F->args()) {
2748 MVT VT = TLI.getSimpleValueType(Arg.getType());
2750 const TargetRegisterClass *RC;
2751 if (VT >= MVT::i1 && VT <= MVT::i32) {
2752 SrcReg = Registers[0][GPRIdx++];
2753 RC = &AArch64::GPR32RegClass;
2755 } else if (VT == MVT::i64) {
2756 SrcReg = Registers[1][GPRIdx++];
2757 RC = &AArch64::GPR64RegClass;
2758 } else if (VT == MVT::f16) {
2759 SrcReg = Registers[2][FPRIdx++];
2760 RC = &AArch64::FPR16RegClass;
2761 } else if (VT == MVT::f32) {
2762 SrcReg = Registers[3][FPRIdx++];
2763 RC = &AArch64::FPR32RegClass;
2764 } else if ((VT == MVT::f64) || VT.is64BitVector()) {
2765 SrcReg = Registers[4][FPRIdx++];
2766 RC = &AArch64::FPR64RegClass;
2767 } else if (VT.is128BitVector()) {
2768 SrcReg = Registers[5][FPRIdx++];
2769 RC = &AArch64::FPR128RegClass;
2771 llvm_unreachable("Unexpected value type.");
2773 unsigned DstReg = FuncInfo.MF->addLiveIn(SrcReg, RC);
2774 // FIXME: Unfortunately it's necessary to emit a copy from the livein copy.
2775 // Without this, EmitLiveInCopies may eliminate the livein if its only
2776 // use is a bitcast (which isn't turned into an instruction).
2777 unsigned ResultReg = createResultReg(RC);
2778 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2779 TII.get(TargetOpcode::COPY), ResultReg)
2780 .addReg(DstReg, getKillRegState(true));
2781 updateValueMap(&Arg, ResultReg);
2786 bool AArch64FastISel::processCallArgs(CallLoweringInfo &CLI,
2787 SmallVectorImpl<MVT> &OutVTs,
2788 unsigned &NumBytes) {
2789 CallingConv::ID CC = CLI.CallConv;
2790 SmallVector<CCValAssign, 16> ArgLocs;
2791 CCState CCInfo(CC, false, *FuncInfo.MF, ArgLocs, *Context);
2792 CCInfo.AnalyzeCallOperands(OutVTs, CLI.OutFlags, CCAssignFnForCall(CC));
2794 // Get a count of how many bytes are to be pushed on the stack.
2795 NumBytes = CCInfo.getNextStackOffset();
2797 // Issue CALLSEQ_START
2798 unsigned AdjStackDown = TII.getCallFrameSetupOpcode();
2799 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackDown))
2802 // Process the args.
2803 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2804 CCValAssign &VA = ArgLocs[i];
2805 const Value *ArgVal = CLI.OutVals[VA.getValNo()];
2806 MVT ArgVT = OutVTs[VA.getValNo()];
2808 unsigned ArgReg = getRegForValue(ArgVal);
2812 // Handle arg promotion: SExt, ZExt, AExt.
2813 switch (VA.getLocInfo()) {
2814 case CCValAssign::Full:
2816 case CCValAssign::SExt: {
2817 MVT DestVT = VA.getLocVT();
2819 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/false);
2824 case CCValAssign::AExt:
2825 // Intentional fall-through.
2826 case CCValAssign::ZExt: {
2827 MVT DestVT = VA.getLocVT();
2829 ArgReg = emitIntExt(SrcVT, ArgReg, DestVT, /*isZExt=*/true);
2835 llvm_unreachable("Unknown arg promotion!");
2838 // Now copy/store arg to correct locations.
2839 if (VA.isRegLoc() && !VA.needsCustom()) {
2840 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2841 TII.get(TargetOpcode::COPY), VA.getLocReg()).addReg(ArgReg);
2842 CLI.OutRegs.push_back(VA.getLocReg());
2843 } else if (VA.needsCustom()) {
2844 // FIXME: Handle custom args.
2847 assert(VA.isMemLoc() && "Assuming store on stack.");
2849 // Don't emit stores for undef values.
2850 if (isa<UndefValue>(ArgVal))
2853 // Need to store on the stack.
2854 unsigned ArgSize = (ArgVT.getSizeInBits() + 7) / 8;
2856 unsigned BEAlign = 0;
2857 if (ArgSize < 8 && !Subtarget->isLittleEndian())
2858 BEAlign = 8 - ArgSize;
2861 Addr.setKind(Address::RegBase);
2862 Addr.setReg(AArch64::SP);
2863 Addr.setOffset(VA.getLocMemOffset() + BEAlign);
2865 unsigned Alignment = DL.getABITypeAlignment(ArgVal->getType());
2866 MachineMemOperand *MMO = FuncInfo.MF->getMachineMemOperand(
2867 MachinePointerInfo::getStack(Addr.getOffset()),
2868 MachineMemOperand::MOStore, ArgVT.getStoreSize(), Alignment);
2870 if (!emitStore(ArgVT, ArgReg, Addr, MMO))
2877 bool AArch64FastISel::finishCall(CallLoweringInfo &CLI, MVT RetVT,
2878 unsigned NumBytes) {
2879 CallingConv::ID CC = CLI.CallConv;
2881 // Issue CALLSEQ_END
2882 unsigned AdjStackUp = TII.getCallFrameDestroyOpcode();
2883 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AdjStackUp))
2884 .addImm(NumBytes).addImm(0);
2886 // Now the return value.
2887 if (RetVT != MVT::isVoid) {
2888 SmallVector<CCValAssign, 16> RVLocs;
2889 CCState CCInfo(CC, false, *FuncInfo.MF, RVLocs, *Context);
2890 CCInfo.AnalyzeCallResult(RetVT, CCAssignFnForCall(CC));
2892 // Only handle a single return value.
2893 if (RVLocs.size() != 1)
2896 // Copy all of the result registers out of their specified physreg.
2897 MVT CopyVT = RVLocs[0].getValVT();
2898 unsigned ResultReg = createResultReg(TLI.getRegClassFor(CopyVT));
2899 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
2900 TII.get(TargetOpcode::COPY), ResultReg)
2901 .addReg(RVLocs[0].getLocReg());
2902 CLI.InRegs.push_back(RVLocs[0].getLocReg());
2904 CLI.ResultReg = ResultReg;
2905 CLI.NumResultRegs = 1;
2911 bool AArch64FastISel::fastLowerCall(CallLoweringInfo &CLI) {
2912 CallingConv::ID CC = CLI.CallConv;
2913 bool IsTailCall = CLI.IsTailCall;
2914 bool IsVarArg = CLI.IsVarArg;
2915 const Value *Callee = CLI.Callee;
2916 const char *SymName = CLI.SymName;
2918 if (!Callee && !SymName)
2921 // Allow SelectionDAG isel to handle tail calls.
2925 CodeModel::Model CM = TM.getCodeModel();
2926 // Only support the small and large code model.
2927 if (CM != CodeModel::Small && CM != CodeModel::Large)
2930 // FIXME: Add large code model support for ELF.
2931 if (CM == CodeModel::Large && !Subtarget->isTargetMachO())
2934 // Let SDISel handle vararg functions.
2938 // FIXME: Only handle *simple* calls for now.
2940 if (CLI.RetTy->isVoidTy())
2941 RetVT = MVT::isVoid;
2942 else if (!isTypeLegal(CLI.RetTy, RetVT))
2945 for (auto Flag : CLI.OutFlags)
2946 if (Flag.isInReg() || Flag.isSRet() || Flag.isNest() || Flag.isByVal())
2949 // Set up the argument vectors.
2950 SmallVector<MVT, 16> OutVTs;
2951 OutVTs.reserve(CLI.OutVals.size());
2953 for (auto *Val : CLI.OutVals) {
2955 if (!isTypeLegal(Val->getType(), VT) &&
2956 !(VT == MVT::i1 || VT == MVT::i8 || VT == MVT::i16))
2959 // We don't handle vector parameters yet.
2960 if (VT.isVector() || VT.getSizeInBits() > 64)
2963 OutVTs.push_back(VT);
2967 if (Callee && !computeCallAddress(Callee, Addr))
2970 // Handle the arguments now that we've gotten them.
2972 if (!processCallArgs(CLI, OutVTs, NumBytes))
2976 MachineInstrBuilder MIB;
2977 if (CM == CodeModel::Small) {
2978 const MCInstrDesc &II = TII.get(Addr.getReg() ? AArch64::BLR : AArch64::BL);
2979 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II);
2981 MIB.addExternalSymbol(SymName, 0);
2982 else if (Addr.getGlobalValue())
2983 MIB.addGlobalAddress(Addr.getGlobalValue(), 0, 0);
2984 else if (Addr.getReg()) {
2985 unsigned Reg = constrainOperandRegClass(II, Addr.getReg(), 0);
2990 unsigned CallReg = 0;
2992 unsigned ADRPReg = createResultReg(&AArch64::GPR64commonRegClass);
2993 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::ADRP),
2995 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGE);
2997 CallReg = createResultReg(&AArch64::GPR64RegClass);
2998 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::LDRXui),
3001 .addExternalSymbol(SymName, AArch64II::MO_GOT | AArch64II::MO_PAGEOFF |
3003 } else if (Addr.getGlobalValue())
3004 CallReg = materializeGV(Addr.getGlobalValue());
3005 else if (Addr.getReg())
3006 CallReg = Addr.getReg();
3011 const MCInstrDesc &II = TII.get(AArch64::BLR);
3012 CallReg = constrainOperandRegClass(II, CallReg, 0);
3013 MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, II).addReg(CallReg);
3016 // Add implicit physical register uses to the call.
3017 for (auto Reg : CLI.OutRegs)
3018 MIB.addReg(Reg, RegState::Implicit);
3020 // Add a register mask with the call-preserved registers.
3021 // Proper defs for return values will be added by setPhysRegsDeadExcept().
3022 MIB.addRegMask(TRI.getCallPreservedMask(CC));
3026 // Finish off the call including any return values.
3027 return finishCall(CLI, RetVT, NumBytes);
3030 bool AArch64FastISel::isMemCpySmall(uint64_t Len, unsigned Alignment) {
3032 return Len / Alignment <= 4;
3037 bool AArch64FastISel::tryEmitSmallMemCpy(Address Dest, Address Src,
3038 uint64_t Len, unsigned Alignment) {
3039 // Make sure we don't bloat code by inlining very large memcpy's.
3040 if (!isMemCpySmall(Len, Alignment))
3043 int64_t UnscaledOffset = 0;
3044 Address OrigDest = Dest;
3045 Address OrigSrc = Src;
3049 if (!Alignment || Alignment >= 8) {
3060 // Bound based on alignment.
3061 if (Len >= 4 && Alignment == 4)
3063 else if (Len >= 2 && Alignment == 2)
3070 unsigned ResultReg = emitLoad(VT, VT, Src);
3074 if (!emitStore(VT, ResultReg, Dest))
3077 int64_t Size = VT.getSizeInBits() / 8;
3079 UnscaledOffset += Size;
3081 // We need to recompute the unscaled offset for each iteration.
3082 Dest.setOffset(OrigDest.getOffset() + UnscaledOffset);
3083 Src.setOffset(OrigSrc.getOffset() + UnscaledOffset);
3089 /// \brief Check if it is possible to fold the condition from the XALU intrinsic
3090 /// into the user. The condition code will only be updated on success.
3091 bool AArch64FastISel::foldXALUIntrinsic(AArch64CC::CondCode &CC,
3092 const Instruction *I,
3093 const Value *Cond) {
3094 if (!isa<ExtractValueInst>(Cond))
3097 const auto *EV = cast<ExtractValueInst>(Cond);
3098 if (!isa<IntrinsicInst>(EV->getAggregateOperand()))
3101 const auto *II = cast<IntrinsicInst>(EV->getAggregateOperand());
3103 const Function *Callee = II->getCalledFunction();
3105 cast<StructType>(Callee->getReturnType())->getTypeAtIndex(0U);
3106 if (!isTypeLegal(RetTy, RetVT))
3109 if (RetVT != MVT::i32 && RetVT != MVT::i64)
3112 const Value *LHS = II->getArgOperand(0);
3113 const Value *RHS = II->getArgOperand(1);
3115 // Canonicalize immediate to the RHS.
3116 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3117 isCommutativeIntrinsic(II))
3118 std::swap(LHS, RHS);
3120 // Simplify multiplies.
3121 unsigned IID = II->getIntrinsicID();
3125 case Intrinsic::smul_with_overflow:
3126 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3127 if (C->getValue() == 2)
3128 IID = Intrinsic::sadd_with_overflow;
3130 case Intrinsic::umul_with_overflow:
3131 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3132 if (C->getValue() == 2)
3133 IID = Intrinsic::uadd_with_overflow;
3137 AArch64CC::CondCode TmpCC;
3141 case Intrinsic::sadd_with_overflow:
3142 case Intrinsic::ssub_with_overflow:
3143 TmpCC = AArch64CC::VS;
3145 case Intrinsic::uadd_with_overflow:
3146 TmpCC = AArch64CC::HS;
3148 case Intrinsic::usub_with_overflow:
3149 TmpCC = AArch64CC::LO;
3151 case Intrinsic::smul_with_overflow:
3152 case Intrinsic::umul_with_overflow:
3153 TmpCC = AArch64CC::NE;
3157 // Check if both instructions are in the same basic block.
3158 if (!isValueAvailable(II))
3161 // Make sure nothing is in the way
3162 BasicBlock::const_iterator Start = I;
3163 BasicBlock::const_iterator End = II;
3164 for (auto Itr = std::prev(Start); Itr != End; --Itr) {
3165 // We only expect extractvalue instructions between the intrinsic and the
3166 // instruction to be selected.
3167 if (!isa<ExtractValueInst>(Itr))
3170 // Check that the extractvalue operand comes from the intrinsic.
3171 const auto *EVI = cast<ExtractValueInst>(Itr);
3172 if (EVI->getAggregateOperand() != II)
3180 bool AArch64FastISel::fastLowerIntrinsicCall(const IntrinsicInst *II) {
3181 // FIXME: Handle more intrinsics.
3182 switch (II->getIntrinsicID()) {
3183 default: return false;
3184 case Intrinsic::frameaddress: {
3185 MachineFrameInfo *MFI = FuncInfo.MF->getFrameInfo();
3186 MFI->setFrameAddressIsTaken(true);
3188 const AArch64RegisterInfo *RegInfo =
3189 static_cast<const AArch64RegisterInfo *>(
3190 TM.getSubtargetImpl()->getRegisterInfo());
3191 unsigned FramePtr = RegInfo->getFrameRegister(*(FuncInfo.MF));
3192 unsigned SrcReg = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3193 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3194 TII.get(TargetOpcode::COPY), SrcReg).addReg(FramePtr);
3195 // Recursively load frame address
3201 unsigned Depth = cast<ConstantInt>(II->getOperand(0))->getZExtValue();
3203 DestReg = fastEmitInst_ri(AArch64::LDRXui, &AArch64::GPR64RegClass,
3204 SrcReg, /*IsKill=*/true, 0);
3205 assert(DestReg && "Unexpected LDR instruction emission failure.");
3209 updateValueMap(II, SrcReg);
3212 case Intrinsic::memcpy:
3213 case Intrinsic::memmove: {
3214 const auto *MTI = cast<MemTransferInst>(II);
3215 // Don't handle volatile.
3216 if (MTI->isVolatile())
3219 // Disable inlining for memmove before calls to ComputeAddress. Otherwise,
3220 // we would emit dead code because we don't currently handle memmoves.
3221 bool IsMemCpy = (II->getIntrinsicID() == Intrinsic::memcpy);
3222 if (isa<ConstantInt>(MTI->getLength()) && IsMemCpy) {
3223 // Small memcpy's are common enough that we want to do them without a call
3225 uint64_t Len = cast<ConstantInt>(MTI->getLength())->getZExtValue();
3226 unsigned Alignment = MTI->getAlignment();
3227 if (isMemCpySmall(Len, Alignment)) {
3229 if (!computeAddress(MTI->getRawDest(), Dest) ||
3230 !computeAddress(MTI->getRawSource(), Src))
3232 if (tryEmitSmallMemCpy(Dest, Src, Len, Alignment))
3237 if (!MTI->getLength()->getType()->isIntegerTy(64))
3240 if (MTI->getSourceAddressSpace() > 255 || MTI->getDestAddressSpace() > 255)
3241 // Fast instruction selection doesn't support the special
3245 const char *IntrMemName = isa<MemCpyInst>(II) ? "memcpy" : "memmove";
3246 return lowerCallTo(II, IntrMemName, II->getNumArgOperands() - 2);
3248 case Intrinsic::memset: {
3249 const MemSetInst *MSI = cast<MemSetInst>(II);
3250 // Don't handle volatile.
3251 if (MSI->isVolatile())
3254 if (!MSI->getLength()->getType()->isIntegerTy(64))
3257 if (MSI->getDestAddressSpace() > 255)
3258 // Fast instruction selection doesn't support the special
3262 return lowerCallTo(II, "memset", II->getNumArgOperands() - 2);
3264 case Intrinsic::sin:
3265 case Intrinsic::cos:
3266 case Intrinsic::pow: {
3268 if (!isTypeLegal(II->getType(), RetVT))
3271 if (RetVT != MVT::f32 && RetVT != MVT::f64)
3274 static const RTLIB::Libcall LibCallTable[3][2] = {
3275 { RTLIB::SIN_F32, RTLIB::SIN_F64 },
3276 { RTLIB::COS_F32, RTLIB::COS_F64 },
3277 { RTLIB::POW_F32, RTLIB::POW_F64 }
3280 bool Is64Bit = RetVT == MVT::f64;
3281 switch (II->getIntrinsicID()) {
3283 llvm_unreachable("Unexpected intrinsic.");
3284 case Intrinsic::sin:
3285 LC = LibCallTable[0][Is64Bit];
3287 case Intrinsic::cos:
3288 LC = LibCallTable[1][Is64Bit];
3290 case Intrinsic::pow:
3291 LC = LibCallTable[2][Is64Bit];
3296 Args.reserve(II->getNumArgOperands());
3298 // Populate the argument list.
3299 for (auto &Arg : II->arg_operands()) {
3302 Entry.Ty = Arg->getType();
3303 Args.push_back(Entry);
3306 CallLoweringInfo CLI;
3307 CLI.setCallee(TLI.getLibcallCallingConv(LC), II->getType(),
3308 TLI.getLibcallName(LC), std::move(Args));
3309 if (!lowerCallTo(CLI))
3311 updateValueMap(II, CLI.ResultReg);
3314 case Intrinsic::fabs: {
3316 if (!isTypeLegal(II->getType(), VT))
3320 switch (VT.SimpleTy) {
3324 Opc = AArch64::FABSSr;
3327 Opc = AArch64::FABSDr;
3330 unsigned SrcReg = getRegForValue(II->getOperand(0));
3333 bool SrcRegIsKill = hasTrivialKill(II->getOperand(0));
3334 unsigned ResultReg = createResultReg(TLI.getRegClassFor(VT));
3335 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(Opc), ResultReg)
3336 .addReg(SrcReg, getKillRegState(SrcRegIsKill));
3337 updateValueMap(II, ResultReg);
3340 case Intrinsic::trap: {
3341 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc, TII.get(AArch64::BRK))
3345 case Intrinsic::sqrt: {
3346 Type *RetTy = II->getCalledFunction()->getReturnType();
3349 if (!isTypeLegal(RetTy, VT))
3352 unsigned Op0Reg = getRegForValue(II->getOperand(0));
3355 bool Op0IsKill = hasTrivialKill(II->getOperand(0));
3357 unsigned ResultReg = fastEmit_r(VT, VT, ISD::FSQRT, Op0Reg, Op0IsKill);
3361 updateValueMap(II, ResultReg);
3364 case Intrinsic::sadd_with_overflow:
3365 case Intrinsic::uadd_with_overflow:
3366 case Intrinsic::ssub_with_overflow:
3367 case Intrinsic::usub_with_overflow:
3368 case Intrinsic::smul_with_overflow:
3369 case Intrinsic::umul_with_overflow: {
3370 // This implements the basic lowering of the xalu with overflow intrinsics.
3371 const Function *Callee = II->getCalledFunction();
3372 auto *Ty = cast<StructType>(Callee->getReturnType());
3373 Type *RetTy = Ty->getTypeAtIndex(0U);
3376 if (!isTypeLegal(RetTy, VT))
3379 if (VT != MVT::i32 && VT != MVT::i64)
3382 const Value *LHS = II->getArgOperand(0);
3383 const Value *RHS = II->getArgOperand(1);
3384 // Canonicalize immediate to the RHS.
3385 if (isa<ConstantInt>(LHS) && !isa<ConstantInt>(RHS) &&
3386 isCommutativeIntrinsic(II))
3387 std::swap(LHS, RHS);
3389 // Simplify multiplies.
3390 unsigned IID = II->getIntrinsicID();
3394 case Intrinsic::smul_with_overflow:
3395 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3396 if (C->getValue() == 2) {
3397 IID = Intrinsic::sadd_with_overflow;
3401 case Intrinsic::umul_with_overflow:
3402 if (const auto *C = dyn_cast<ConstantInt>(RHS))
3403 if (C->getValue() == 2) {
3404 IID = Intrinsic::uadd_with_overflow;
3410 unsigned ResultReg1 = 0, ResultReg2 = 0, MulReg = 0;
3411 AArch64CC::CondCode CC = AArch64CC::Invalid;
3413 default: llvm_unreachable("Unexpected intrinsic!");
3414 case Intrinsic::sadd_with_overflow:
3415 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3418 case Intrinsic::uadd_with_overflow:
3419 ResultReg1 = emitAdd(VT, LHS, RHS, /*SetFlags=*/true);
3422 case Intrinsic::ssub_with_overflow:
3423 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3426 case Intrinsic::usub_with_overflow:
3427 ResultReg1 = emitSub(VT, LHS, RHS, /*SetFlags=*/true);
3430 case Intrinsic::smul_with_overflow: {
3432 unsigned LHSReg = getRegForValue(LHS);
3435 bool LHSIsKill = hasTrivialKill(LHS);
3437 unsigned RHSReg = getRegForValue(RHS);
3440 bool RHSIsKill = hasTrivialKill(RHS);
3442 if (VT == MVT::i32) {
3443 MulReg = emitSMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3444 unsigned ShiftReg = emitLSR_ri(MVT::i64, MVT::i64, MulReg,
3445 /*IsKill=*/false, 32);
3446 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3448 ShiftReg = fastEmitInst_extractsubreg(VT, ShiftReg, /*IsKill=*/true,
3450 emitSubs_rs(VT, ShiftReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3451 AArch64_AM::ASR, 31, /*WantResult=*/false);
3453 assert(VT == MVT::i64 && "Unexpected value type.");
3454 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3455 unsigned SMULHReg = fastEmit_rr(VT, VT, ISD::MULHS, LHSReg, LHSIsKill,
3457 emitSubs_rs(VT, SMULHReg, /*IsKill=*/true, MulReg, /*IsKill=*/false,
3458 AArch64_AM::ASR, 63, /*WantResult=*/false);
3462 case Intrinsic::umul_with_overflow: {
3464 unsigned LHSReg = getRegForValue(LHS);
3467 bool LHSIsKill = hasTrivialKill(LHS);
3469 unsigned RHSReg = getRegForValue(RHS);
3472 bool RHSIsKill = hasTrivialKill(RHS);
3474 if (VT == MVT::i32) {
3475 MulReg = emitUMULL_rr(MVT::i64, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3476 emitSubs_rs(MVT::i64, AArch64::XZR, /*IsKill=*/true, MulReg,
3477 /*IsKill=*/false, AArch64_AM::LSR, 32,
3478 /*WantResult=*/false);
3479 MulReg = fastEmitInst_extractsubreg(VT, MulReg, /*IsKill=*/true,
3482 assert(VT == MVT::i64 && "Unexpected value type.");
3483 MulReg = emitMul_rr(VT, LHSReg, LHSIsKill, RHSReg, RHSIsKill);
3484 unsigned UMULHReg = fastEmit_rr(VT, VT, ISD::MULHU, LHSReg, LHSIsKill,
3486 emitSubs_rr(VT, AArch64::XZR, /*IsKill=*/true, UMULHReg,
3487 /*IsKill=*/false, /*WantResult=*/false);
3494 ResultReg1 = createResultReg(TLI.getRegClassFor(VT));
3495 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3496 TII.get(TargetOpcode::COPY), ResultReg1).addReg(MulReg);
3499 ResultReg2 = fastEmitInst_rri(AArch64::CSINCWr, &AArch64::GPR32RegClass,
3500 AArch64::WZR, /*IsKill=*/true, AArch64::WZR,
3501 /*IsKill=*/true, getInvertedCondCode(CC));
3503 assert((ResultReg1 + 1) == ResultReg2 &&
3504 "Nonconsecutive result registers.");
3505 updateValueMap(II, ResultReg1, 2);
3512 bool AArch64FastISel::selectRet(const Instruction *I) {
3513 const ReturnInst *Ret = cast<ReturnInst>(I);
3514 const Function &F = *I->getParent()->getParent();
3516 if (!FuncInfo.CanLowerReturn)
3522 // Build a list of return value registers.
3523 SmallVector<unsigned, 4> RetRegs;
3525 if (Ret->getNumOperands() > 0) {
3526 CallingConv::ID CC = F.getCallingConv();
3527 SmallVector<ISD::OutputArg, 4> Outs;
3528 GetReturnInfo(F.getReturnType(), F.getAttributes(), Outs, TLI);
3530 // Analyze operands of the call, assigning locations to each operand.
3531 SmallVector<CCValAssign, 16> ValLocs;
3532 CCState CCInfo(CC, F.isVarArg(), *FuncInfo.MF, ValLocs, I->getContext());
3533 CCAssignFn *RetCC = CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
3534 : RetCC_AArch64_AAPCS;
3535 CCInfo.AnalyzeReturn(Outs, RetCC);
3537 // Only handle a single return value for now.
3538 if (ValLocs.size() != 1)
3541 CCValAssign &VA = ValLocs[0];
3542 const Value *RV = Ret->getOperand(0);
3544 // Don't bother handling odd stuff for now.
3545 if ((VA.getLocInfo() != CCValAssign::Full) &&
3546 (VA.getLocInfo() != CCValAssign::BCvt))
3549 // Only handle register returns for now.
3553 unsigned Reg = getRegForValue(RV);
3557 unsigned SrcReg = Reg + VA.getValNo();
3558 unsigned DestReg = VA.getLocReg();
3559 // Avoid a cross-class copy. This is very unlikely.
3560 if (!MRI.getRegClass(SrcReg)->contains(DestReg))
3563 EVT RVEVT = TLI.getValueType(RV->getType());
3564 if (!RVEVT.isSimple())
3567 // Vectors (of > 1 lane) in big endian need tricky handling.
3568 if (RVEVT.isVector() && RVEVT.getVectorNumElements() > 1 &&
3569 !Subtarget->isLittleEndian())
3572 MVT RVVT = RVEVT.getSimpleVT();
3573 if (RVVT == MVT::f128)
3576 MVT DestVT = VA.getValVT();
3577 // Special handling for extended integers.
3578 if (RVVT != DestVT) {
3579 if (RVVT != MVT::i1 && RVVT != MVT::i8 && RVVT != MVT::i16)
3582 if (!Outs[0].Flags.isZExt() && !Outs[0].Flags.isSExt())
3585 bool IsZExt = Outs[0].Flags.isZExt();
3586 SrcReg = emitIntExt(RVVT, SrcReg, DestVT, IsZExt);
3592 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3593 TII.get(TargetOpcode::COPY), DestReg).addReg(SrcReg);
3595 // Add register to return instruction.
3596 RetRegs.push_back(VA.getLocReg());
3599 MachineInstrBuilder MIB = BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3600 TII.get(AArch64::RET_ReallyLR));
3601 for (unsigned i = 0, e = RetRegs.size(); i != e; ++i)
3602 MIB.addReg(RetRegs[i], RegState::Implicit);
3606 bool AArch64FastISel::selectTrunc(const Instruction *I) {
3607 Type *DestTy = I->getType();
3608 Value *Op = I->getOperand(0);
3609 Type *SrcTy = Op->getType();
3611 EVT SrcEVT = TLI.getValueType(SrcTy, true);
3612 EVT DestEVT = TLI.getValueType(DestTy, true);
3613 if (!SrcEVT.isSimple())
3615 if (!DestEVT.isSimple())
3618 MVT SrcVT = SrcEVT.getSimpleVT();
3619 MVT DestVT = DestEVT.getSimpleVT();
3621 if (SrcVT != MVT::i64 && SrcVT != MVT::i32 && SrcVT != MVT::i16 &&
3624 if (DestVT != MVT::i32 && DestVT != MVT::i16 && DestVT != MVT::i8 &&
3628 unsigned SrcReg = getRegForValue(Op);
3631 bool SrcIsKill = hasTrivialKill(Op);
3633 // If we're truncating from i64 to a smaller non-legal type then generate an
3634 // AND. Otherwise, we know the high bits are undefined and a truncate only
3635 // generate a COPY. We cannot mark the source register also as result
3636 // register, because this can incorrectly transfer the kill flag onto the
3639 if (SrcVT == MVT::i64) {
3641 switch (DestVT.SimpleTy) {
3643 // Trunc i64 to i32 is handled by the target-independent fast-isel.
3655 // Issue an extract_subreg to get the lower 32-bits.
3656 unsigned Reg32 = fastEmitInst_extractsubreg(MVT::i32, SrcReg, SrcIsKill,
3658 // Create the AND instruction which performs the actual truncation.
3659 ResultReg = emitAnd_ri(MVT::i32, Reg32, /*IsKill=*/true, Mask);
3660 assert(ResultReg && "Unexpected AND instruction emission failure.");
3662 ResultReg = createResultReg(&AArch64::GPR32RegClass);
3663 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3664 TII.get(TargetOpcode::COPY), ResultReg)
3665 .addReg(SrcReg, getKillRegState(SrcIsKill));
3668 updateValueMap(I, ResultReg);
3672 unsigned AArch64FastISel::emiti1Ext(unsigned SrcReg, MVT DestVT, bool IsZExt) {
3673 assert((DestVT == MVT::i8 || DestVT == MVT::i16 || DestVT == MVT::i32 ||
3674 DestVT == MVT::i64) &&
3675 "Unexpected value type.");
3676 // Handle i8 and i16 as i32.
3677 if (DestVT == MVT::i8 || DestVT == MVT::i16)
3681 unsigned ResultReg = emitAnd_ri(MVT::i32, SrcReg, /*TODO:IsKill=*/false, 1);
3682 assert(ResultReg && "Unexpected AND instruction emission failure.");
3683 if (DestVT == MVT::i64) {
3684 // We're ZExt i1 to i64. The ANDWri Wd, Ws, #1 implicitly clears the
3685 // upper 32 bits. Emit a SUBREG_TO_REG to extend from Wd to Xd.
3686 unsigned Reg64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
3687 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3688 TII.get(AArch64::SUBREG_TO_REG), Reg64)
3691 .addImm(AArch64::sub_32);
3696 if (DestVT == MVT::i64) {
3697 // FIXME: We're SExt i1 to i64.
3700 return fastEmitInst_rii(AArch64::SBFMWri, &AArch64::GPR32RegClass, SrcReg,
3701 /*TODO:IsKill=*/false, 0, 0);
3705 unsigned AArch64FastISel::emitMul_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3706 unsigned Op1, bool Op1IsKill) {
3708 switch (RetVT.SimpleTy) {
3714 Opc = AArch64::MADDWrrr; ZReg = AArch64::WZR; break;
3716 Opc = AArch64::MADDXrrr; ZReg = AArch64::XZR; break;
3719 const TargetRegisterClass *RC =
3720 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3721 return fastEmitInst_rrr(Opc, RC, Op0, Op0IsKill, Op1, Op1IsKill,
3722 /*IsKill=*/ZReg, true);
3725 unsigned AArch64FastISel::emitSMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3726 unsigned Op1, bool Op1IsKill) {
3727 if (RetVT != MVT::i64)
3730 return fastEmitInst_rrr(AArch64::SMADDLrrr, &AArch64::GPR64RegClass,
3731 Op0, Op0IsKill, Op1, Op1IsKill,
3732 AArch64::XZR, /*IsKill=*/true);
3735 unsigned AArch64FastISel::emitUMULL_rr(MVT RetVT, unsigned Op0, bool Op0IsKill,
3736 unsigned Op1, bool Op1IsKill) {
3737 if (RetVT != MVT::i64)
3740 return fastEmitInst_rrr(AArch64::UMADDLrrr, &AArch64::GPR64RegClass,
3741 Op0, Op0IsKill, Op1, Op1IsKill,
3742 AArch64::XZR, /*IsKill=*/true);
3745 unsigned AArch64FastISel::emitLSL_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3746 unsigned Op1Reg, bool Op1IsKill) {
3748 bool NeedTrunc = false;
3750 switch (RetVT.SimpleTy) {
3752 case MVT::i8: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xff; break;
3753 case MVT::i16: Opc = AArch64::LSLVWr; NeedTrunc = true; Mask = 0xffff; break;
3754 case MVT::i32: Opc = AArch64::LSLVWr; break;
3755 case MVT::i64: Opc = AArch64::LSLVXr; break;
3758 const TargetRegisterClass *RC =
3759 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3761 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3764 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3767 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3771 unsigned AArch64FastISel::emitLSL_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3772 bool Op0IsKill, uint64_t Shift,
3774 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3775 "Unexpected source/return type pair.");
3776 assert((SrcVT == MVT::i1 || SrcVT == MVT::i8 || SrcVT == MVT::i16 ||
3777 SrcVT == MVT::i32 || SrcVT == MVT::i64) &&
3778 "Unexpected source value type.");
3779 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3780 RetVT == MVT::i64) && "Unexpected return value type.");
3782 bool Is64Bit = (RetVT == MVT::i64);
3783 unsigned RegSize = Is64Bit ? 64 : 32;
3784 unsigned DstBits = RetVT.getSizeInBits();
3785 unsigned SrcBits = SrcVT.getSizeInBits();
3787 // Don't deal with undefined shifts.
3788 if (Shift >= DstBits)
3791 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3792 // {S|U}BFM Wd, Wn, #r, #s
3793 // Wd<32+s-r,32-r> = Wn<s:0> when r > s
3795 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3796 // %2 = shl i16 %1, 4
3797 // Wd<32+7-28,32-28> = Wn<7:0> <- clamp s to 7
3798 // 0b1111_1111_1111_1111__1111_1010_1010_0000 sext
3799 // 0b0000_0000_0000_0000__0000_0101_0101_0000 sext | zext
3800 // 0b0000_0000_0000_0000__0000_1010_1010_0000 zext
3802 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3803 // %2 = shl i16 %1, 8
3804 // Wd<32+7-24,32-24> = Wn<7:0>
3805 // 0b1111_1111_1111_1111__1010_1010_0000_0000 sext
3806 // 0b0000_0000_0000_0000__0101_0101_0000_0000 sext | zext
3807 // 0b0000_0000_0000_0000__1010_1010_0000_0000 zext
3809 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3810 // %2 = shl i16 %1, 12
3811 // Wd<32+3-20,32-20> = Wn<3:0>
3812 // 0b1111_1111_1111_1111__1010_0000_0000_0000 sext
3813 // 0b0000_0000_0000_0000__0101_0000_0000_0000 sext | zext
3814 // 0b0000_0000_0000_0000__1010_0000_0000_0000 zext
3816 unsigned ImmR = RegSize - Shift;
3817 // Limit the width to the length of the source type.
3818 unsigned ImmS = std::min<unsigned>(SrcBits - 1, DstBits - 1 - Shift);
3819 static const unsigned OpcTable[2][2] = {
3820 {AArch64::SBFMWri, AArch64::SBFMXri},
3821 {AArch64::UBFMWri, AArch64::UBFMXri}
3823 unsigned Opc = OpcTable[IsZext][Is64Bit];
3824 const TargetRegisterClass *RC =
3825 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3826 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3827 unsigned TmpReg = MRI.createVirtualRegister(RC);
3828 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3829 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3831 .addReg(Op0, getKillRegState(Op0IsKill))
3832 .addImm(AArch64::sub_32);
3836 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3839 unsigned AArch64FastISel::emitLSR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3840 unsigned Op1Reg, bool Op1IsKill) {
3842 bool NeedTrunc = false;
3844 switch (RetVT.SimpleTy) {
3846 case MVT::i8: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xff; break;
3847 case MVT::i16: Opc = AArch64::LSRVWr; NeedTrunc = true; Mask = 0xffff; break;
3848 case MVT::i32: Opc = AArch64::LSRVWr; break;
3849 case MVT::i64: Opc = AArch64::LSRVXr; break;
3852 const TargetRegisterClass *RC =
3853 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3855 Op0Reg = emitAnd_ri(MVT::i32, Op0Reg, Op0IsKill, Mask);
3856 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3857 Op0IsKill = Op1IsKill = true;
3859 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3862 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3866 unsigned AArch64FastISel::emitLSR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3867 bool Op0IsKill, uint64_t Shift,
3869 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3870 "Unexpected source/return type pair.");
3871 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3872 SrcVT == MVT::i64) && "Unexpected source value type.");
3873 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3874 RetVT == MVT::i64) && "Unexpected return value type.");
3876 bool Is64Bit = (RetVT == MVT::i64);
3877 unsigned RegSize = Is64Bit ? 64 : 32;
3878 unsigned DstBits = RetVT.getSizeInBits();
3879 unsigned SrcBits = SrcVT.getSizeInBits();
3881 // Don't deal with undefined shifts.
3882 if (Shift >= DstBits)
3885 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3886 // {S|U}BFM Wd, Wn, #r, #s
3887 // Wd<s-r:0> = Wn<s:r> when r <= s
3889 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3890 // %2 = lshr i16 %1, 4
3891 // Wd<7-4:0> = Wn<7:4>
3892 // 0b0000_0000_0000_0000__0000_1111_1111_1010 sext
3893 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
3894 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
3896 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3897 // %2 = lshr i16 %1, 8
3898 // Wd<7-7,0> = Wn<7:7>
3899 // 0b0000_0000_0000_0000__0000_0000_1111_1111 sext
3900 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3901 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3903 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3904 // %2 = lshr i16 %1, 12
3905 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
3906 // 0b0000_0000_0000_0000__0000_0000_0000_1111 sext
3907 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
3908 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
3910 if (Shift >= SrcBits && IsZExt)
3911 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
3913 // It is not possible to fold a sign-extend into the LShr instruction. In this
3914 // case emit a sign-extend.
3916 Op0 = emitIntExt(SrcVT, Op0, RetVT, IsZExt);
3921 SrcBits = SrcVT.getSizeInBits();
3925 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
3926 unsigned ImmS = SrcBits - 1;
3927 static const unsigned OpcTable[2][2] = {
3928 {AArch64::SBFMWri, AArch64::SBFMXri},
3929 {AArch64::UBFMWri, AArch64::UBFMXri}
3931 unsigned Opc = OpcTable[IsZExt][Is64Bit];
3932 const TargetRegisterClass *RC =
3933 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3934 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
3935 unsigned TmpReg = MRI.createVirtualRegister(RC);
3936 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
3937 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
3939 .addReg(Op0, getKillRegState(Op0IsKill))
3940 .addImm(AArch64::sub_32);
3944 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
3947 unsigned AArch64FastISel::emitASR_rr(MVT RetVT, unsigned Op0Reg, bool Op0IsKill,
3948 unsigned Op1Reg, bool Op1IsKill) {
3950 bool NeedTrunc = false;
3952 switch (RetVT.SimpleTy) {
3954 case MVT::i8: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xff; break;
3955 case MVT::i16: Opc = AArch64::ASRVWr; NeedTrunc = true; Mask = 0xffff; break;
3956 case MVT::i32: Opc = AArch64::ASRVWr; break;
3957 case MVT::i64: Opc = AArch64::ASRVXr; break;
3960 const TargetRegisterClass *RC =
3961 (RetVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
3963 Op0Reg = emitIntExt(RetVT, Op0Reg, MVT::i32, /*IsZExt=*/false);
3964 Op1Reg = emitAnd_ri(MVT::i32, Op1Reg, Op1IsKill, Mask);
3965 Op0IsKill = Op1IsKill = true;
3967 unsigned ResultReg = fastEmitInst_rr(Opc, RC, Op0Reg, Op0IsKill, Op1Reg,
3970 ResultReg = emitAnd_ri(MVT::i32, ResultReg, /*IsKill=*/true, Mask);
3974 unsigned AArch64FastISel::emitASR_ri(MVT RetVT, MVT SrcVT, unsigned Op0,
3975 bool Op0IsKill, uint64_t Shift,
3977 assert(RetVT.SimpleTy >= SrcVT.SimpleTy &&
3978 "Unexpected source/return type pair.");
3979 assert((SrcVT == MVT::i8 || SrcVT == MVT::i16 || SrcVT == MVT::i32 ||
3980 SrcVT == MVT::i64) && "Unexpected source value type.");
3981 assert((RetVT == MVT::i8 || RetVT == MVT::i16 || RetVT == MVT::i32 ||
3982 RetVT == MVT::i64) && "Unexpected return value type.");
3984 bool Is64Bit = (RetVT == MVT::i64);
3985 unsigned RegSize = Is64Bit ? 64 : 32;
3986 unsigned DstBits = RetVT.getSizeInBits();
3987 unsigned SrcBits = SrcVT.getSizeInBits();
3989 // Don't deal with undefined shifts.
3990 if (Shift >= DstBits)
3993 // For immediate shifts we can fold the zero-/sign-extension into the shift.
3994 // {S|U}BFM Wd, Wn, #r, #s
3995 // Wd<s-r:0> = Wn<s:r> when r <= s
3997 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
3998 // %2 = ashr i16 %1, 4
3999 // Wd<7-4:0> = Wn<7:4>
4000 // 0b1111_1111_1111_1111__1111_1111_1111_1010 sext
4001 // 0b0000_0000_0000_0000__0000_0000_0000_0101 sext | zext
4002 // 0b0000_0000_0000_0000__0000_0000_0000_1010 zext
4004 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4005 // %2 = ashr i16 %1, 8
4006 // Wd<7-7,0> = Wn<7:7>
4007 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4008 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4009 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4011 // %1 = {s|z}ext i8 {0b1010_1010|0b0101_0101} to i16
4012 // %2 = ashr i16 %1, 12
4013 // Wd<7-7,0> = Wn<7:7> <- clamp r to 7
4014 // 0b1111_1111_1111_1111__1111_1111_1111_1111 sext
4015 // 0b0000_0000_0000_0000__0000_0000_0000_0000 sext
4016 // 0b0000_0000_0000_0000__0000_0000_0000_0000 zext
4018 if (Shift >= SrcBits && IsZExt)
4019 return materializeInt(ConstantInt::get(*Context, APInt(RegSize, 0)), RetVT);
4021 unsigned ImmR = std::min<unsigned>(SrcBits - 1, Shift);
4022 unsigned ImmS = SrcBits - 1;
4023 static const unsigned OpcTable[2][2] = {
4024 {AArch64::SBFMWri, AArch64::SBFMXri},
4025 {AArch64::UBFMWri, AArch64::UBFMXri}
4027 unsigned Opc = OpcTable[IsZExt][Is64Bit];
4028 const TargetRegisterClass *RC =
4029 Is64Bit ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4030 if (SrcVT.SimpleTy <= MVT::i32 && RetVT == MVT::i64) {
4031 unsigned TmpReg = MRI.createVirtualRegister(RC);
4032 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4033 TII.get(AArch64::SUBREG_TO_REG), TmpReg)
4035 .addReg(Op0, getKillRegState(Op0IsKill))
4036 .addImm(AArch64::sub_32);
4040 return fastEmitInst_rii(Opc, RC, Op0, Op0IsKill, ImmR, ImmS);
4043 unsigned AArch64FastISel::emitIntExt(MVT SrcVT, unsigned SrcReg, MVT DestVT,
4045 assert(DestVT != MVT::i1 && "ZeroExt/SignExt an i1?");
4047 // FastISel does not have plumbing to deal with extensions where the SrcVT or
4048 // DestVT are odd things, so test to make sure that they are both types we can
4049 // handle (i1/i8/i16/i32 for SrcVT and i8/i16/i32/i64 for DestVT), otherwise
4050 // bail out to SelectionDAG.
4051 if (((DestVT != MVT::i8) && (DestVT != MVT::i16) &&
4052 (DestVT != MVT::i32) && (DestVT != MVT::i64)) ||
4053 ((SrcVT != MVT::i1) && (SrcVT != MVT::i8) &&
4054 (SrcVT != MVT::i16) && (SrcVT != MVT::i32)))
4060 switch (SrcVT.SimpleTy) {
4064 return emiti1Ext(SrcReg, DestVT, IsZExt);
4066 if (DestVT == MVT::i64)
4067 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4069 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4073 if (DestVT == MVT::i64)
4074 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4076 Opc = IsZExt ? AArch64::UBFMWri : AArch64::SBFMWri;
4080 assert(DestVT == MVT::i64 && "IntExt i32 to i32?!?");
4081 Opc = IsZExt ? AArch64::UBFMXri : AArch64::SBFMXri;
4086 // Handle i8 and i16 as i32.
4087 if (DestVT == MVT::i8 || DestVT == MVT::i16)
4089 else if (DestVT == MVT::i64) {
4090 unsigned Src64 = MRI.createVirtualRegister(&AArch64::GPR64RegClass);
4091 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4092 TII.get(AArch64::SUBREG_TO_REG), Src64)
4095 .addImm(AArch64::sub_32);
4099 const TargetRegisterClass *RC =
4100 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4101 return fastEmitInst_rii(Opc, RC, SrcReg, /*TODO:IsKill=*/false, 0, Imm);
4104 static bool isZExtLoad(const MachineInstr *LI) {
4105 switch (LI->getOpcode()) {
4108 case AArch64::LDURBBi:
4109 case AArch64::LDURHHi:
4110 case AArch64::LDURWi:
4111 case AArch64::LDRBBui:
4112 case AArch64::LDRHHui:
4113 case AArch64::LDRWui:
4114 case AArch64::LDRBBroX:
4115 case AArch64::LDRHHroX:
4116 case AArch64::LDRWroX:
4117 case AArch64::LDRBBroW:
4118 case AArch64::LDRHHroW:
4119 case AArch64::LDRWroW:
4124 static bool isSExtLoad(const MachineInstr *LI) {
4125 switch (LI->getOpcode()) {
4128 case AArch64::LDURSBWi:
4129 case AArch64::LDURSHWi:
4130 case AArch64::LDURSBXi:
4131 case AArch64::LDURSHXi:
4132 case AArch64::LDURSWi:
4133 case AArch64::LDRSBWui:
4134 case AArch64::LDRSHWui:
4135 case AArch64::LDRSBXui:
4136 case AArch64::LDRSHXui:
4137 case AArch64::LDRSWui:
4138 case AArch64::LDRSBWroX:
4139 case AArch64::LDRSHWroX:
4140 case AArch64::LDRSBXroX:
4141 case AArch64::LDRSHXroX:
4142 case AArch64::LDRSWroX:
4143 case AArch64::LDRSBWroW:
4144 case AArch64::LDRSHWroW:
4145 case AArch64::LDRSBXroW:
4146 case AArch64::LDRSHXroW:
4147 case AArch64::LDRSWroW:
4152 bool AArch64FastISel::optimizeIntExtLoad(const Instruction *I, MVT RetVT,
4154 const auto *LI = dyn_cast<LoadInst>(I->getOperand(0));
4155 if (!LI || !LI->hasOneUse())
4158 // Check if the load instruction has already been selected.
4159 unsigned Reg = lookUpRegForValue(LI);
4163 MachineInstr *MI = MRI.getUniqueVRegDef(Reg);
4167 // Check if the correct load instruction has been emitted - SelectionDAG might
4168 // have emitted a zero-extending load, but we need a sign-extending load.
4169 bool IsZExt = isa<ZExtInst>(I);
4170 const auto *LoadMI = MI;
4171 if (LoadMI->getOpcode() == TargetOpcode::COPY &&
4172 LoadMI->getOperand(1).getSubReg() == AArch64::sub_32) {
4173 unsigned LoadReg = MI->getOperand(1).getReg();
4174 LoadMI = MRI.getUniqueVRegDef(LoadReg);
4175 assert(LoadMI && "Expected valid instruction");
4177 if (!(IsZExt && isZExtLoad(LoadMI)) && !(!IsZExt && isSExtLoad(LoadMI)))
4180 // Nothing to be done.
4181 if (RetVT != MVT::i64 || SrcVT > MVT::i32) {
4182 updateValueMap(I, Reg);
4187 unsigned Reg64 = createResultReg(&AArch64::GPR64RegClass);
4188 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4189 TII.get(AArch64::SUBREG_TO_REG), Reg64)
4191 .addReg(Reg, getKillRegState(true))
4192 .addImm(AArch64::sub_32);
4195 assert((MI->getOpcode() == TargetOpcode::COPY &&
4196 MI->getOperand(1).getSubReg() == AArch64::sub_32) &&
4197 "Expected copy instruction");
4198 Reg = MI->getOperand(1).getReg();
4199 MI->eraseFromParent();
4201 updateValueMap(I, Reg);
4205 bool AArch64FastISel::selectIntExt(const Instruction *I) {
4206 assert((isa<ZExtInst>(I) || isa<SExtInst>(I)) &&
4207 "Unexpected integer extend instruction.");
4210 if (!isTypeSupported(I->getType(), RetVT))
4213 if (!isTypeSupported(I->getOperand(0)->getType(), SrcVT))
4216 // Try to optimize already sign-/zero-extended values from load instructions.
4217 if (optimizeIntExtLoad(I, RetVT, SrcVT))
4220 unsigned SrcReg = getRegForValue(I->getOperand(0));
4223 bool SrcIsKill = hasTrivialKill(I->getOperand(0));
4225 // Try to optimize already sign-/zero-extended values from function arguments.
4226 bool IsZExt = isa<ZExtInst>(I);
4227 if (const auto *Arg = dyn_cast<Argument>(I->getOperand(0))) {
4228 if ((IsZExt && Arg->hasZExtAttr()) || (!IsZExt && Arg->hasSExtAttr())) {
4229 if (RetVT == MVT::i64 && SrcVT != MVT::i64) {
4230 unsigned ResultReg = createResultReg(&AArch64::GPR64RegClass);
4231 BuildMI(*FuncInfo.MBB, FuncInfo.InsertPt, DbgLoc,
4232 TII.get(AArch64::SUBREG_TO_REG), ResultReg)
4234 .addReg(SrcReg, getKillRegState(SrcIsKill))
4235 .addImm(AArch64::sub_32);
4238 // Conservatively clear all kill flags from all uses, because we are
4239 // replacing a sign-/zero-extend instruction at IR level with a nop at MI
4240 // level. The result of the instruction at IR level might have been
4241 // trivially dead, which is now not longer true.
4242 unsigned UseReg = lookUpRegForValue(I);
4244 MRI.clearKillFlags(UseReg);
4246 updateValueMap(I, SrcReg);
4251 unsigned ResultReg = emitIntExt(SrcVT, SrcReg, RetVT, IsZExt);
4255 updateValueMap(I, ResultReg);
4259 bool AArch64FastISel::selectRem(const Instruction *I, unsigned ISDOpcode) {
4260 EVT DestEVT = TLI.getValueType(I->getType(), true);
4261 if (!DestEVT.isSimple())
4264 MVT DestVT = DestEVT.getSimpleVT();
4265 if (DestVT != MVT::i64 && DestVT != MVT::i32)
4269 bool Is64bit = (DestVT == MVT::i64);
4270 switch (ISDOpcode) {
4274 DivOpc = Is64bit ? AArch64::SDIVXr : AArch64::SDIVWr;
4277 DivOpc = Is64bit ? AArch64::UDIVXr : AArch64::UDIVWr;
4280 unsigned MSubOpc = Is64bit ? AArch64::MSUBXrrr : AArch64::MSUBWrrr;
4281 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4284 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4286 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4289 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4291 const TargetRegisterClass *RC =
4292 (DestVT == MVT::i64) ? &AArch64::GPR64RegClass : &AArch64::GPR32RegClass;
4293 unsigned QuotReg = fastEmitInst_rr(DivOpc, RC, Src0Reg, /*IsKill=*/false,
4294 Src1Reg, /*IsKill=*/false);
4295 assert(QuotReg && "Unexpected DIV instruction emission failure.");
4296 // The remainder is computed as numerator - (quotient * denominator) using the
4297 // MSUB instruction.
4298 unsigned ResultReg = fastEmitInst_rrr(MSubOpc, RC, QuotReg, /*IsKill=*/true,
4299 Src1Reg, Src1IsKill, Src0Reg,
4301 updateValueMap(I, ResultReg);
4305 bool AArch64FastISel::selectMul(const Instruction *I) {
4307 if (!isTypeSupported(I->getType(), VT, /*IsVectorAllowed=*/true))
4311 return selectBinaryOp(I, ISD::MUL);
4313 const Value *Src0 = I->getOperand(0);
4314 const Value *Src1 = I->getOperand(1);
4315 if (const auto *C = dyn_cast<ConstantInt>(Src0))
4316 if (C->getValue().isPowerOf2())
4317 std::swap(Src0, Src1);
4319 // Try to simplify to a shift instruction.
4320 if (const auto *C = dyn_cast<ConstantInt>(Src1))
4321 if (C->getValue().isPowerOf2()) {
4322 uint64_t ShiftVal = C->getValue().logBase2();
4325 if (const auto *ZExt = dyn_cast<ZExtInst>(Src0)) {
4326 if (!isIntExtFree(ZExt)) {
4328 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), VT)) {
4331 Src0 = ZExt->getOperand(0);
4334 } else if (const auto *SExt = dyn_cast<SExtInst>(Src0)) {
4335 if (!isIntExtFree(SExt)) {
4337 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), VT)) {
4340 Src0 = SExt->getOperand(0);
4345 unsigned Src0Reg = getRegForValue(Src0);
4348 bool Src0IsKill = hasTrivialKill(Src0);
4350 unsigned ResultReg =
4351 emitLSL_ri(VT, SrcVT, Src0Reg, Src0IsKill, ShiftVal, IsZExt);
4354 updateValueMap(I, ResultReg);
4359 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4362 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4364 unsigned Src1Reg = getRegForValue(I->getOperand(1));
4367 bool Src1IsKill = hasTrivialKill(I->getOperand(1));
4369 unsigned ResultReg = emitMul_rr(VT, Src0Reg, Src0IsKill, Src1Reg, Src1IsKill);
4374 updateValueMap(I, ResultReg);
4378 bool AArch64FastISel::selectShift(const Instruction *I) {
4380 if (!isTypeSupported(I->getType(), RetVT, /*IsVectorAllowed=*/true))
4383 if (RetVT.isVector())
4384 return selectOperator(I, I->getOpcode());
4386 if (const auto *C = dyn_cast<ConstantInt>(I->getOperand(1))) {
4387 unsigned ResultReg = 0;
4388 uint64_t ShiftVal = C->getZExtValue();
4390 bool IsZExt = (I->getOpcode() == Instruction::AShr) ? false : true;
4391 const Value *Op0 = I->getOperand(0);
4392 if (const auto *ZExt = dyn_cast<ZExtInst>(Op0)) {
4393 if (!isIntExtFree(ZExt)) {
4395 if (isValueAvailable(ZExt) && isTypeSupported(ZExt->getSrcTy(), TmpVT)) {
4398 Op0 = ZExt->getOperand(0);
4401 } else if (const auto *SExt = dyn_cast<SExtInst>(Op0)) {
4402 if (!isIntExtFree(SExt)) {
4404 if (isValueAvailable(SExt) && isTypeSupported(SExt->getSrcTy(), TmpVT)) {
4407 Op0 = SExt->getOperand(0);
4412 unsigned Op0Reg = getRegForValue(Op0);
4415 bool Op0IsKill = hasTrivialKill(Op0);
4417 switch (I->getOpcode()) {
4418 default: llvm_unreachable("Unexpected instruction.");
4419 case Instruction::Shl:
4420 ResultReg = emitLSL_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4422 case Instruction::AShr:
4423 ResultReg = emitASR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4425 case Instruction::LShr:
4426 ResultReg = emitLSR_ri(RetVT, SrcVT, Op0Reg, Op0IsKill, ShiftVal, IsZExt);
4432 updateValueMap(I, ResultReg);
4436 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4439 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4441 unsigned Op1Reg = getRegForValue(I->getOperand(1));
4444 bool Op1IsKill = hasTrivialKill(I->getOperand(1));
4446 unsigned ResultReg = 0;
4447 switch (I->getOpcode()) {
4448 default: llvm_unreachable("Unexpected instruction.");
4449 case Instruction::Shl:
4450 ResultReg = emitLSL_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4452 case Instruction::AShr:
4453 ResultReg = emitASR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4455 case Instruction::LShr:
4456 ResultReg = emitLSR_rr(RetVT, Op0Reg, Op0IsKill, Op1Reg, Op1IsKill);
4463 updateValueMap(I, ResultReg);
4467 bool AArch64FastISel::selectBitCast(const Instruction *I) {
4470 if (!isTypeLegal(I->getOperand(0)->getType(), SrcVT))
4472 if (!isTypeLegal(I->getType(), RetVT))
4476 if (RetVT == MVT::f32 && SrcVT == MVT::i32)
4477 Opc = AArch64::FMOVWSr;
4478 else if (RetVT == MVT::f64 && SrcVT == MVT::i64)
4479 Opc = AArch64::FMOVXDr;
4480 else if (RetVT == MVT::i32 && SrcVT == MVT::f32)
4481 Opc = AArch64::FMOVSWr;
4482 else if (RetVT == MVT::i64 && SrcVT == MVT::f64)
4483 Opc = AArch64::FMOVDXr;
4487 const TargetRegisterClass *RC = nullptr;
4488 switch (RetVT.SimpleTy) {
4489 default: llvm_unreachable("Unexpected value type.");
4490 case MVT::i32: RC = &AArch64::GPR32RegClass; break;
4491 case MVT::i64: RC = &AArch64::GPR64RegClass; break;
4492 case MVT::f32: RC = &AArch64::FPR32RegClass; break;
4493 case MVT::f64: RC = &AArch64::FPR64RegClass; break;
4495 unsigned Op0Reg = getRegForValue(I->getOperand(0));
4498 bool Op0IsKill = hasTrivialKill(I->getOperand(0));
4499 unsigned ResultReg = fastEmitInst_r(Opc, RC, Op0Reg, Op0IsKill);
4504 updateValueMap(I, ResultReg);
4508 bool AArch64FastISel::selectFRem(const Instruction *I) {
4510 if (!isTypeLegal(I->getType(), RetVT))
4514 switch (RetVT.SimpleTy) {
4518 LC = RTLIB::REM_F32;
4521 LC = RTLIB::REM_F64;
4526 Args.reserve(I->getNumOperands());
4528 // Populate the argument list.
4529 for (auto &Arg : I->operands()) {
4532 Entry.Ty = Arg->getType();
4533 Args.push_back(Entry);
4536 CallLoweringInfo CLI;
4537 CLI.setCallee(TLI.getLibcallCallingConv(LC), I->getType(),
4538 TLI.getLibcallName(LC), std::move(Args));
4539 if (!lowerCallTo(CLI))
4541 updateValueMap(I, CLI.ResultReg);
4545 bool AArch64FastISel::selectSDiv(const Instruction *I) {
4547 if (!isTypeLegal(I->getType(), VT))
4550 if (!isa<ConstantInt>(I->getOperand(1)))
4551 return selectBinaryOp(I, ISD::SDIV);
4553 const APInt &C = cast<ConstantInt>(I->getOperand(1))->getValue();
4554 if ((VT != MVT::i32 && VT != MVT::i64) || !C ||
4555 !(C.isPowerOf2() || (-C).isPowerOf2()))
4556 return selectBinaryOp(I, ISD::SDIV);
4558 unsigned Lg2 = C.countTrailingZeros();
4559 unsigned Src0Reg = getRegForValue(I->getOperand(0));
4562 bool Src0IsKill = hasTrivialKill(I->getOperand(0));
4564 if (cast<BinaryOperator>(I)->isExact()) {
4565 unsigned ResultReg = emitASR_ri(VT, VT, Src0Reg, Src0IsKill, Lg2);
4568 updateValueMap(I, ResultReg);
4572 int64_t Pow2MinusOne = (1ULL << Lg2) - 1;
4573 unsigned AddReg = emitAdd_ri_(VT, Src0Reg, /*IsKill=*/false, Pow2MinusOne);
4577 // (Src0 < 0) ? Pow2 - 1 : 0;
4578 if (!emitICmp_ri(VT, Src0Reg, /*IsKill=*/false, 0))
4582 const TargetRegisterClass *RC;
4583 if (VT == MVT::i64) {
4584 SelectOpc = AArch64::CSELXr;
4585 RC = &AArch64::GPR64RegClass;
4587 SelectOpc = AArch64::CSELWr;
4588 RC = &AArch64::GPR32RegClass;
4590 unsigned SelectReg =
4591 fastEmitInst_rri(SelectOpc, RC, AddReg, /*IsKill=*/true, Src0Reg,
4592 Src0IsKill, AArch64CC::LT);
4596 // Divide by Pow2 --> ashr. If we're dividing by a negative value we must also
4597 // negate the result.
4598 unsigned ZeroReg = (VT == MVT::i64) ? AArch64::XZR : AArch64::WZR;
4601 ResultReg = emitAddSub_rs(/*UseAdd=*/false, VT, ZeroReg, /*IsKill=*/true,
4602 SelectReg, /*IsKill=*/true, AArch64_AM::ASR, Lg2);
4604 ResultReg = emitASR_ri(VT, VT, SelectReg, /*IsKill=*/true, Lg2);
4609 updateValueMap(I, ResultReg);
4613 /// This is mostly a copy of the existing FastISel GEP code, but we have to
4614 /// duplicate it for AArch64, because otherwise we would bail out even for
4615 /// simple cases. This is because the standard fastEmit functions don't cover
4616 /// MUL at all and ADD is lowered very inefficientily.
4617 bool AArch64FastISel::selectGetElementPtr(const Instruction *I) {
4618 unsigned N = getRegForValue(I->getOperand(0));
4621 bool NIsKill = hasTrivialKill(I->getOperand(0));
4623 // Keep a running tab of the total offset to coalesce multiple N = N + Offset
4624 // into a single N = N + TotalOffset.
4625 uint64_t TotalOffs = 0;
4626 Type *Ty = I->getOperand(0)->getType();
4627 MVT VT = TLI.getPointerTy();
4628 for (auto OI = std::next(I->op_begin()), E = I->op_end(); OI != E; ++OI) {
4629 const Value *Idx = *OI;
4630 if (auto *StTy = dyn_cast<StructType>(Ty)) {
4631 unsigned Field = cast<ConstantInt>(Idx)->getZExtValue();
4634 TotalOffs += DL.getStructLayout(StTy)->getElementOffset(Field);
4635 Ty = StTy->getElementType(Field);
4637 Ty = cast<SequentialType>(Ty)->getElementType();
4638 // If this is a constant subscript, handle it quickly.
4639 if (const auto *CI = dyn_cast<ConstantInt>(Idx)) {
4644 DL.getTypeAllocSize(Ty) * cast<ConstantInt>(CI)->getSExtValue();
4648 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4655 // N = N + Idx * ElementSize;
4656 uint64_t ElementSize = DL.getTypeAllocSize(Ty);
4657 std::pair<unsigned, bool> Pair = getRegForGEPIndex(Idx);
4658 unsigned IdxN = Pair.first;
4659 bool IdxNIsKill = Pair.second;
4663 if (ElementSize != 1) {
4664 unsigned C = fastEmit_i(VT, VT, ISD::Constant, ElementSize);
4667 IdxN = emitMul_rr(VT, IdxN, IdxNIsKill, C, true);
4672 N = fastEmit_rr(VT, VT, ISD::ADD, N, NIsKill, IdxN, IdxNIsKill);
4678 N = emitAdd_ri_(VT, N, NIsKill, TotalOffs);
4682 updateValueMap(I, N);
4686 bool AArch64FastISel::fastSelectInstruction(const Instruction *I) {
4687 switch (I->getOpcode()) {
4690 case Instruction::Add:
4691 case Instruction::Sub:
4692 return selectAddSub(I);
4693 case Instruction::Mul:
4694 return selectMul(I);
4695 case Instruction::SDiv:
4696 return selectSDiv(I);
4697 case Instruction::SRem:
4698 if (!selectBinaryOp(I, ISD::SREM))
4699 return selectRem(I, ISD::SREM);
4701 case Instruction::URem:
4702 if (!selectBinaryOp(I, ISD::UREM))
4703 return selectRem(I, ISD::UREM);
4705 case Instruction::Shl:
4706 case Instruction::LShr:
4707 case Instruction::AShr:
4708 return selectShift(I);
4709 case Instruction::And:
4710 case Instruction::Or:
4711 case Instruction::Xor:
4712 return selectLogicalOp(I);
4713 case Instruction::Br:
4714 return selectBranch(I);
4715 case Instruction::IndirectBr:
4716 return selectIndirectBr(I);
4717 case Instruction::BitCast:
4718 if (!FastISel::selectBitCast(I))
4719 return selectBitCast(I);
4721 case Instruction::FPToSI:
4722 if (!selectCast(I, ISD::FP_TO_SINT))
4723 return selectFPToInt(I, /*Signed=*/true);
4725 case Instruction::FPToUI:
4726 return selectFPToInt(I, /*Signed=*/false);
4727 case Instruction::ZExt:
4728 case Instruction::SExt:
4729 return selectIntExt(I);
4730 case Instruction::Trunc:
4731 if (!selectCast(I, ISD::TRUNCATE))
4732 return selectTrunc(I);
4734 case Instruction::FPExt:
4735 return selectFPExt(I);
4736 case Instruction::FPTrunc:
4737 return selectFPTrunc(I);
4738 case Instruction::SIToFP:
4739 if (!selectCast(I, ISD::SINT_TO_FP))
4740 return selectIntToFP(I, /*Signed=*/true);
4742 case Instruction::UIToFP:
4743 return selectIntToFP(I, /*Signed=*/false);
4744 case Instruction::Load:
4745 return selectLoad(I);
4746 case Instruction::Store:
4747 return selectStore(I);
4748 case Instruction::FCmp:
4749 case Instruction::ICmp:
4750 return selectCmp(I);
4751 case Instruction::Select:
4752 return selectSelect(I);
4753 case Instruction::Ret:
4754 return selectRet(I);
4755 case Instruction::FRem:
4756 return selectFRem(I);
4757 case Instruction::GetElementPtr:
4758 return selectGetElementPtr(I);
4761 // fall-back to target-independent instruction selection.
4762 return selectOperator(I, I->getOpcode());
4763 // Silence warnings.
4764 (void)&CC_AArch64_DarwinPCS_VarArg;
4768 llvm::FastISel *AArch64::createFastISel(FunctionLoweringInfo &FuncInfo,
4769 const TargetLibraryInfo *LibInfo) {
4770 return new AArch64FastISel(FuncInfo, LibInfo);